es6.js 4.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers;
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers;
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. if (this._getFromCache(baseName)) {
  196. this._prepareEffect();
  197. return;
  198. }
  199. var vertexSource;
  200. var fragmentSource;
  201. if (baseName.vertexElement) {
  202. vertexSource = document.getElementById(baseName.vertexElement);
  203. if (!vertexSource) {
  204. vertexSource = baseName.vertexElement;
  205. }
  206. }
  207. else {
  208. vertexSource = baseName.vertex || baseName;
  209. }
  210. if (baseName.fragmentElement) {
  211. fragmentSource = document.getElementById(baseName.fragmentElement);
  212. if (!fragmentSource) {
  213. fragmentSource = baseName.fragmentElement;
  214. }
  215. }
  216. else {
  217. fragmentSource = baseName.fragment || baseName;
  218. }
  219. var finalVertexCode;
  220. this._loadVertexShaderAsync(vertexSource)
  221. .then(function (vertexCode) {
  222. return _this._processIncludesAsync(vertexCode);
  223. })
  224. .then(function (vertexCodeWithIncludes) {
  225. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  226. return _this._loadFragmentShaderAsync(fragmentSource);
  227. })
  228. .then(function (fragmentCode) {
  229. return _this._processIncludesAsync(fragmentCode);
  230. })
  231. .then(function (fragmentCodeWithIncludes) {
  232. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  233. if (baseName) {
  234. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  235. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  236. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  237. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  238. }
  239. else {
  240. _this._vertexSourceCode = finalVertexCode;
  241. _this._fragmentSourceCode = migratedFragmentCode;
  242. }
  243. _this._setInCache(baseName);
  244. _this._prepareEffect();
  245. });
  246. }
  247. Effect.prototype._getSourceCacheKey = function (baseName) {
  248. var cacheKey = baseName;
  249. if (this._indexParameters) {
  250. for (var key in this._indexParameters) {
  251. if (this._indexParameters.hasOwnProperty(key)) {
  252. cacheKey += "|";
  253. cacheKey += key;
  254. cacheKey += "_";
  255. cacheKey += this._indexParameters[key];
  256. }
  257. }
  258. }
  259. return cacheKey;
  260. };
  261. Effect.prototype._getFromCache = function (baseName) {
  262. if (typeof baseName !== "string") {
  263. return false;
  264. }
  265. var cacheKey = this._getSourceCacheKey(baseName);
  266. var sources = Effect._sourceCache[cacheKey];
  267. if (!sources) {
  268. return false;
  269. }
  270. this._vertexSourceCode = sources.vertex;
  271. this._fragmentSourceCode = sources.fragment;
  272. return true;
  273. };
  274. Effect.prototype._setInCache = function (baseName) {
  275. if (typeof baseName !== "string") {
  276. return;
  277. }
  278. var cacheKey = this._getSourceCacheKey(baseName);
  279. Effect._sourceCache[cacheKey] = {
  280. vertex: this._vertexSourceCode,
  281. fragment: this._fragmentSourceCode
  282. };
  283. };
  284. Object.defineProperty(Effect.prototype, "key", {
  285. /**
  286. * Unique key for this effect
  287. */
  288. get: function () {
  289. return this._key;
  290. },
  291. enumerable: true,
  292. configurable: true
  293. });
  294. /**
  295. * If the effect has been compiled and prepared.
  296. * @returns if the effect is compiled and prepared.
  297. */
  298. Effect.prototype.isReady = function () {
  299. return this._isReady;
  300. };
  301. /**
  302. * The engine the effect was initialized with.
  303. * @returns the engine.
  304. */
  305. Effect.prototype.getEngine = function () {
  306. return this._engine;
  307. };
  308. /**
  309. * The compiled webGL program for the effect
  310. * @returns the webGL program.
  311. */
  312. Effect.prototype.getProgram = function () {
  313. return this._program;
  314. };
  315. /**
  316. * The set of names of attribute variables for the shader.
  317. * @returns An array of attribute names.
  318. */
  319. Effect.prototype.getAttributesNames = function () {
  320. return this._attributesNames;
  321. };
  322. /**
  323. * Returns the attribute at the given index.
  324. * @param index The index of the attribute.
  325. * @returns The location of the attribute.
  326. */
  327. Effect.prototype.getAttributeLocation = function (index) {
  328. return this._attributes[index];
  329. };
  330. /**
  331. * Returns the attribute based on the name of the variable.
  332. * @param name of the attribute to look up.
  333. * @returns the attribute location.
  334. */
  335. Effect.prototype.getAttributeLocationByName = function (name) {
  336. var index = this._attributesNames.indexOf(name);
  337. return this._attributes[index];
  338. };
  339. /**
  340. * The number of attributes.
  341. * @returns the numnber of attributes.
  342. */
  343. Effect.prototype.getAttributesCount = function () {
  344. return this._attributes.length;
  345. };
  346. /**
  347. * Gets the index of a uniform variable.
  348. * @param uniformName of the uniform to look up.
  349. * @returns the index.
  350. */
  351. Effect.prototype.getUniformIndex = function (uniformName) {
  352. return this._uniformsNames.indexOf(uniformName);
  353. };
  354. /**
  355. * Returns the attribute based on the name of the variable.
  356. * @param uniformName of the uniform to look up.
  357. * @returns the location of the uniform.
  358. */
  359. Effect.prototype.getUniform = function (uniformName) {
  360. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  361. };
  362. /**
  363. * Returns an array of sampler variable names
  364. * @returns The array of sampler variable neames.
  365. */
  366. Effect.prototype.getSamplers = function () {
  367. return this._samplers;
  368. };
  369. /**
  370. * The error from the last compilation.
  371. * @returns the error string.
  372. */
  373. Effect.prototype.getCompilationError = function () {
  374. return this._compilationError;
  375. };
  376. /**
  377. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  378. * @param func The callback to be used.
  379. */
  380. Effect.prototype.executeWhenCompiled = function (func) {
  381. if (this.isReady()) {
  382. func(this);
  383. return;
  384. }
  385. this.onCompileObservable.add(function (effect) {
  386. func(effect);
  387. });
  388. };
  389. /** @ignore */
  390. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  391. if (BABYLON.Tools.IsWindowObjectExist()) {
  392. // DOM element ?
  393. if (vertex instanceof HTMLElement) {
  394. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  395. return Promise.resolve(vertexCode);
  396. }
  397. }
  398. // Base64 encoded ?
  399. if (vertex.substr(0, 7) === "base64:") {
  400. var vertexBinary = window.atob(vertex.substr(7));
  401. return Promise.resolve(vertexBinary);
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  405. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  406. }
  407. var vertexShaderUrl;
  408. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  409. vertexShaderUrl = vertex;
  410. }
  411. else {
  412. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  413. }
  414. // Vertex shader
  415. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  416. };
  417. /** @ignore */
  418. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  419. if (BABYLON.Tools.IsWindowObjectExist()) {
  420. // DOM element ?
  421. if (fragment instanceof HTMLElement) {
  422. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  423. return Promise.resolve(fragmentCode);
  424. }
  425. }
  426. // Base64 encoded ?
  427. if (fragment.substr(0, 7) === "base64:") {
  428. var fragmentBinary = window.atob(fragment.substr(7));
  429. return Promise.resolve(fragmentBinary);
  430. }
  431. // Is in local store ?
  432. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  433. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. }
  438. var fragmentShaderUrl;
  439. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  440. fragmentShaderUrl = fragment;
  441. }
  442. else {
  443. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  444. }
  445. // Fragment shader
  446. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  447. };
  448. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  449. // Rebuild shaders source code
  450. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  451. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  452. vertexCode = prefix + vertexCode;
  453. fragmentCode = prefix + fragmentCode;
  454. // Number lines of shaders source code
  455. var i = 2;
  456. var regex = /\n/gm;
  457. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  458. i = 2;
  459. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. // Dump shaders name and formatted source code
  461. if (this.name.vertexElement) {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  464. }
  465. else if (this.name.vertex) {
  466. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  467. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  468. }
  469. else {
  470. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  471. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  472. }
  473. };
  474. ;
  475. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  476. var preparedSourceCode = this._processPrecision(sourceCode);
  477. if (this._engine.webGLVersion == 1) {
  478. return preparedSourceCode;
  479. }
  480. // Already converted
  481. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  482. return preparedSourceCode.replace("#version 300 es", "");
  483. }
  484. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  485. // Remove extensions
  486. // #extension GL_OES_standard_derivatives : enable
  487. // #extension GL_EXT_shader_texture_lod : enable
  488. // #extension GL_EXT_frag_depth : enable
  489. // #extension GL_EXT_draw_buffers : require
  490. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  491. var result = preparedSourceCode.replace(regex, "");
  492. // Migrate to GLSL v300
  493. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  494. result = result.replace(/attribute[ \t]/g, "in ");
  495. result = result.replace(/[ \t]attribute/g, " in");
  496. if (isFragment) {
  497. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  498. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  499. result = result.replace(/texture2D\s*\(/g, "texture(");
  500. result = result.replace(/textureCube\s*\(/g, "texture(");
  501. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  502. result = result.replace(/gl_FragColor/g, "glFragColor");
  503. result = result.replace(/gl_FragData/g, "glFragData");
  504. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  505. }
  506. return result;
  507. };
  508. Effect.prototype._processIncludesAsync = function (sourceCode) {
  509. var _this = this;
  510. return new Promise(function (resolve, reject) {
  511. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  512. var match = regex.exec(sourceCode);
  513. var returnValue = sourceCode;
  514. while (match != null) {
  515. var includeFile = match[1];
  516. // Uniform declaration
  517. if (includeFile.indexOf("__decl__") !== -1) {
  518. includeFile = includeFile.replace(/__decl__/, "");
  519. if (_this._engine.supportsUniformBuffers) {
  520. includeFile = includeFile.replace(/Vertex/, "Ubo");
  521. includeFile = includeFile.replace(/Fragment/, "Ubo");
  522. }
  523. includeFile = includeFile + "Declaration";
  524. }
  525. if (Effect.IncludesShadersStore[includeFile]) {
  526. // Substitution
  527. var includeContent = Effect.IncludesShadersStore[includeFile];
  528. if (match[2]) {
  529. var splits = match[3].split(",");
  530. for (var index = 0; index < splits.length; index += 2) {
  531. var source = new RegExp(splits[index], "g");
  532. var dest = splits[index + 1];
  533. includeContent = includeContent.replace(source, dest);
  534. }
  535. }
  536. if (match[4]) {
  537. var indexString = match[5];
  538. if (indexString.indexOf("..") !== -1) {
  539. var indexSplits = indexString.split("..");
  540. var minIndex = parseInt(indexSplits[0]);
  541. var maxIndex = parseInt(indexSplits[1]);
  542. var sourceIncludeContent = includeContent.slice(0);
  543. includeContent = "";
  544. if (isNaN(maxIndex)) {
  545. maxIndex = _this._indexParameters[indexSplits[1]];
  546. }
  547. for (var i = minIndex; i < maxIndex; i++) {
  548. if (!_this._engine.supportsUniformBuffers) {
  549. // Ubo replacement
  550. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  551. return p1 + "{X}";
  552. });
  553. }
  554. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  555. }
  556. }
  557. else {
  558. if (!_this._engine.supportsUniformBuffers) {
  559. // Ubo replacement
  560. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  561. return p1 + "{X}";
  562. });
  563. }
  564. includeContent = includeContent.replace(/\{X\}/g, indexString);
  565. }
  566. }
  567. // Replace
  568. returnValue = returnValue.replace(match[0], includeContent);
  569. }
  570. else {
  571. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  572. _this._engine._loadFileAsync(includeShaderUrl)
  573. .then(function (fileContent) {
  574. Effect.IncludesShadersStore[includeFile] = fileContent;
  575. return _this._processIncludesAsync(returnValue);
  576. })
  577. .then(function (returnValue) {
  578. resolve(returnValue);
  579. });
  580. return;
  581. }
  582. match = regex.exec(sourceCode);
  583. }
  584. resolve(returnValue);
  585. });
  586. };
  587. Effect.prototype._processPrecision = function (source) {
  588. if (source.indexOf("precision highp float") === -1) {
  589. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  590. source = "precision mediump float;\n" + source;
  591. }
  592. else {
  593. source = "precision highp float;\n" + source;
  594. }
  595. }
  596. else {
  597. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  598. source = source.replace("precision highp float", "precision mediump float");
  599. }
  600. }
  601. return source;
  602. };
  603. /**
  604. * Recompiles the webGL program
  605. * @param vertexSourceCode The source code for the vertex shader.
  606. * @param fragmentSourceCode The source code for the fragment shader.
  607. * @param onCompiled Callback called when completed.
  608. * @param onError Callback called on error.
  609. */
  610. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  611. var _this = this;
  612. this._isReady = false;
  613. this._vertexSourceCodeOverride = vertexSourceCode;
  614. this._fragmentSourceCodeOverride = fragmentSourceCode;
  615. this.onError = function (effect, error) {
  616. if (onError) {
  617. onError(error);
  618. }
  619. };
  620. this.onCompiled = function () {
  621. var scenes = _this.getEngine().scenes;
  622. for (var i = 0; i < scenes.length; i++) {
  623. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  624. }
  625. if (onCompiled) {
  626. onCompiled(_this._program);
  627. }
  628. };
  629. this._fallbacks = null;
  630. this._prepareEffect();
  631. };
  632. /**
  633. * Gets the uniform locations of the the specified variable names
  634. * @param names THe names of the variables to lookup.
  635. * @returns Array of locations in the same order as variable names.
  636. */
  637. Effect.prototype.getSpecificUniformLocations = function (names) {
  638. var engine = this._engine;
  639. return engine.getUniforms(this._program, names);
  640. };
  641. /**
  642. * Prepares the effect
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  701. BABYLON.Tools.Error("Error: " + this._compilationError);
  702. if (previousProgram) {
  703. this._program = previousProgram;
  704. this._isReady = true;
  705. if (this.onError) {
  706. this.onError(this, this._compilationError);
  707. }
  708. this.onErrorObservable.notifyObservers(this);
  709. }
  710. if (fallbacks && fallbacks.isMoreFallbacks) {
  711. BABYLON.Tools.Error("Trying next fallback.");
  712. this.defines = fallbacks.reduce(this.defines, this);
  713. this._prepareEffect();
  714. }
  715. else {
  716. if (this.onError) {
  717. this.onError(this, this._compilationError);
  718. }
  719. this.onErrorObservable.notifyObservers(this);
  720. this.onErrorObservable.clear();
  721. // Unbind mesh reference in fallbacks
  722. if (this._fallbacks) {
  723. this._fallbacks.unBindMesh();
  724. }
  725. }
  726. }
  727. };
  728. Object.defineProperty(Effect.prototype, "isSupported", {
  729. /**
  730. * Checks if the effect is supported. (Must be called after compilation)
  731. */
  732. get: function () {
  733. return this._compilationError === "";
  734. },
  735. enumerable: true,
  736. configurable: true
  737. });
  738. /**
  739. * Binds a texture to the engine to be used as output of the shader.
  740. * @param channel Name of the output variable.
  741. * @param texture Texture to bind.
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets an array of textures on the engine to be used in the shader.
  756. * @param channel Name of the variable.
  757. * @param textures Textures to set.
  758. */
  759. Effect.prototype.setTextureArray = function (channel, textures) {
  760. if (this._samplers.indexOf(channel + "Ex") === -1) {
  761. var initialPos = this._samplers.indexOf(channel);
  762. for (var index = 1; index < textures.length; index++) {
  763. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  764. }
  765. }
  766. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  767. };
  768. /**
  769. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  770. * @param channel Name of the sampler variable.
  771. * @param postProcess Post process to get the input texture from.
  772. */
  773. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  774. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  775. };
  776. /** @ignore */
  777. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  778. var cache = this._valueCache[uniformName];
  779. var flag = matrix.updateFlag;
  780. if (cache !== undefined && cache === flag) {
  781. return false;
  782. }
  783. this._valueCache[uniformName] = flag;
  784. return true;
  785. };
  786. /** @ignore */
  787. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  788. var cache = this._valueCache[uniformName];
  789. if (!cache) {
  790. cache = [x, y];
  791. this._valueCache[uniformName] = cache;
  792. return true;
  793. }
  794. var changed = false;
  795. if (cache[0] !== x) {
  796. cache[0] = x;
  797. changed = true;
  798. }
  799. if (cache[1] !== y) {
  800. cache[1] = y;
  801. changed = true;
  802. }
  803. return changed;
  804. };
  805. /** @ignore */
  806. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  807. var cache = this._valueCache[uniformName];
  808. if (!cache) {
  809. cache = [x, y, z];
  810. this._valueCache[uniformName] = cache;
  811. return true;
  812. }
  813. var changed = false;
  814. if (cache[0] !== x) {
  815. cache[0] = x;
  816. changed = true;
  817. }
  818. if (cache[1] !== y) {
  819. cache[1] = y;
  820. changed = true;
  821. }
  822. if (cache[2] !== z) {
  823. cache[2] = z;
  824. changed = true;
  825. }
  826. return changed;
  827. };
  828. /** @ignore */
  829. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  830. var cache = this._valueCache[uniformName];
  831. if (!cache) {
  832. cache = [x, y, z, w];
  833. this._valueCache[uniformName] = cache;
  834. return true;
  835. }
  836. var changed = false;
  837. if (cache[0] !== x) {
  838. cache[0] = x;
  839. changed = true;
  840. }
  841. if (cache[1] !== y) {
  842. cache[1] = y;
  843. changed = true;
  844. }
  845. if (cache[2] !== z) {
  846. cache[2] = z;
  847. changed = true;
  848. }
  849. if (cache[3] !== w) {
  850. cache[3] = w;
  851. changed = true;
  852. }
  853. return changed;
  854. };
  855. /**
  856. * Binds a buffer to a uniform.
  857. * @param buffer Buffer to bind.
  858. * @param name Name of the uniform variable to bind to.
  859. */
  860. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  861. var bufferName = this._uniformBuffersNames[name];
  862. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  863. return;
  864. }
  865. Effect._baseCache[bufferName] = buffer;
  866. this._engine.bindUniformBufferBase(buffer, bufferName);
  867. };
  868. /**
  869. * Binds block to a uniform.
  870. * @param blockName Name of the block to bind.
  871. * @param index Index to bind.
  872. */
  873. Effect.prototype.bindUniformBlock = function (blockName, index) {
  874. this._engine.bindUniformBlock(this._program, blockName, index);
  875. };
  876. /**
  877. * Sets an interger value on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param value Value to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setInt = function (uniformName, value) {
  883. var cache = this._valueCache[uniformName];
  884. if (cache !== undefined && cache === value)
  885. return this;
  886. this._valueCache[uniformName] = value;
  887. this._engine.setInt(this.getUniform(uniformName), value);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray2 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray2(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setIntArray3 = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setIntArray3(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setIntArray4 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setIntArray4(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array on a uniform variable.
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray2 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray2(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1002. * @param uniformName Name of the variable.
  1003. * @param array array to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setArray3 = function (uniformName, array) {
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setArray3(this.getUniform(uniformName), array);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1013. * @param uniformName Name of the variable.
  1014. * @param array array to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setArray4 = function (uniformName, array) {
  1018. this._valueCache[uniformName] = null;
  1019. this._engine.setArray4(this.getUniform(uniformName), array);
  1020. return this;
  1021. };
  1022. /**
  1023. * Sets matrices on a uniform variable.
  1024. * @param uniformName Name of the variable.
  1025. * @param matrices matrices to be set.
  1026. * @returns this effect.
  1027. */
  1028. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1029. if (!matrices) {
  1030. return this;
  1031. }
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1034. return this;
  1035. };
  1036. /**
  1037. * Sets matrix on a uniform variable.
  1038. * @param uniformName Name of the variable.
  1039. * @param matrix matrix to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1043. if (this._cacheMatrix(uniformName, matrix)) {
  1044. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1045. }
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1050. * @param uniformName Name of the variable.
  1051. * @param matrix matrix to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1055. this._valueCache[uniformName] = null;
  1056. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1061. * @param uniformName Name of the variable.
  1062. * @param matrix matrix to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1066. this._valueCache[uniformName] = null;
  1067. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1068. return this;
  1069. };
  1070. /**
  1071. * Sets a float on a uniform variable.
  1072. * @param uniformName Name of the variable.
  1073. * @param value value to be set.
  1074. * @returns this effect.
  1075. */
  1076. Effect.prototype.setFloat = function (uniformName, value) {
  1077. var cache = this._valueCache[uniformName];
  1078. if (cache !== undefined && cache === value)
  1079. return this;
  1080. this._valueCache[uniformName] = value;
  1081. this._engine.setFloat(this.getUniform(uniformName), value);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets a boolean on a uniform variable.
  1086. * @param uniformName Name of the variable.
  1087. * @param bool value to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setBool = function (uniformName, bool) {
  1091. var cache = this._valueCache[uniformName];
  1092. if (cache !== undefined && cache === bool)
  1093. return this;
  1094. this._valueCache[uniformName] = bool;
  1095. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector2 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector2 vector2 to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1105. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1106. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float2 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float2.
  1114. * @param y Second float in float2.
  1115. * @returns this effect.
  1116. */
  1117. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1118. if (this._cacheFloat2(uniformName, x, y)) {
  1119. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1120. }
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets a Vector3 on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param vector3 Value to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1130. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1131. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a float3 on a uniform variable.
  1137. * @param uniformName Name of the variable.
  1138. * @param x First float in float3.
  1139. * @param y Second float in float3.
  1140. * @param z Third float in float3.
  1141. * @returns this effect.
  1142. */
  1143. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1144. if (this._cacheFloat3(uniformName, x, y, z)) {
  1145. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1146. }
  1147. return this;
  1148. };
  1149. /**
  1150. * Sets a Vector4 on a uniform variable.
  1151. * @param uniformName Name of the variable.
  1152. * @param vector4 Value to be set.
  1153. * @returns this effect.
  1154. */
  1155. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1156. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1157. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1158. }
  1159. return this;
  1160. };
  1161. /**
  1162. * Sets a float4 on a uniform variable.
  1163. * @param uniformName Name of the variable.
  1164. * @param x First float in float4.
  1165. * @param y Second float in float4.
  1166. * @param z Third float in float4.
  1167. * @param w Fourth float in float4.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1171. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1172. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color3 on a uniform variable.
  1178. * @param uniformName Name of the variable.
  1179. * @param color3 Value to be set.
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setColor3 = function (uniformName, color3) {
  1183. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1184. this._engine.setColor3(this.getUniform(uniformName), color3);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Sets a Color4 on a uniform variable.
  1190. * @param uniformName Name of the variable.
  1191. * @param color3 Value to be set.
  1192. * @param alpha Alpha value to be set.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1196. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1197. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1198. }
  1199. return this;
  1200. };
  1201. /**
  1202. * Sets a Color4 on a uniform variable
  1203. * @param uniformName defines the name of the variable
  1204. * @param color4 defines the value to be set
  1205. * @returns this effect.
  1206. */
  1207. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1208. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1209. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1210. }
  1211. return this;
  1212. };
  1213. /**
  1214. * Resets the cache of effects.
  1215. */
  1216. Effect.ResetCache = function () {
  1217. Effect._baseCache = {};
  1218. };
  1219. Effect._uniqueIdSeed = 0;
  1220. Effect._baseCache = {};
  1221. Effect._sourceCache = {};
  1222. // Statics
  1223. /**
  1224. * Store of each shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.ShadersStore = {};
  1227. /**
  1228. * Store of each included file for a shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.IncludesShadersStore = {};
  1231. return Effect;
  1232. }());
  1233. BABYLON.Effect = Effect;
  1234. })(BABYLON || (BABYLON = {}));
  1235. //# sourceMappingURL=babylon.effect.js.map
  1236. //# sourceMappingURL=babylon.types.js.map
  1237. var BABYLON;
  1238. (function (BABYLON) {
  1239. var KeyboardEventTypes = /** @class */ (function () {
  1240. function KeyboardEventTypes() {
  1241. }
  1242. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1243. get: function () {
  1244. return KeyboardEventTypes._KEYDOWN;
  1245. },
  1246. enumerable: true,
  1247. configurable: true
  1248. });
  1249. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1250. get: function () {
  1251. return KeyboardEventTypes._KEYUP;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. KeyboardEventTypes._KEYDOWN = 0x01;
  1257. KeyboardEventTypes._KEYUP = 0x02;
  1258. return KeyboardEventTypes;
  1259. }());
  1260. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. function KeyboardInfo(type, event) {
  1263. this.type = type;
  1264. this.event = event;
  1265. }
  1266. return KeyboardInfo;
  1267. }());
  1268. BABYLON.KeyboardInfo = KeyboardInfo;
  1269. /**
  1270. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1271. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1272. */
  1273. var KeyboardInfoPre = /** @class */ (function (_super) {
  1274. __extends(KeyboardInfoPre, _super);
  1275. function KeyboardInfoPre(type, event) {
  1276. var _this = _super.call(this, type, event) || this;
  1277. _this.skipOnPointerObservable = false;
  1278. return _this;
  1279. }
  1280. return KeyboardInfoPre;
  1281. }(KeyboardInfo));
  1282. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1283. })(BABYLON || (BABYLON = {}));
  1284. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1285. var BABYLON;
  1286. (function (BABYLON) {
  1287. var PointerEventTypes = /** @class */ (function () {
  1288. function PointerEventTypes() {
  1289. }
  1290. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1291. get: function () {
  1292. return PointerEventTypes._POINTERDOWN;
  1293. },
  1294. enumerable: true,
  1295. configurable: true
  1296. });
  1297. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1298. get: function () {
  1299. return PointerEventTypes._POINTERUP;
  1300. },
  1301. enumerable: true,
  1302. configurable: true
  1303. });
  1304. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1305. get: function () {
  1306. return PointerEventTypes._POINTERMOVE;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERWHEEL;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERPICK;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERTAP;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERDOUBLETAP;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. PointerEventTypes._POINTERDOWN = 0x01;
  1340. PointerEventTypes._POINTERUP = 0x02;
  1341. PointerEventTypes._POINTERMOVE = 0x04;
  1342. PointerEventTypes._POINTERWHEEL = 0x08;
  1343. PointerEventTypes._POINTERPICK = 0x10;
  1344. PointerEventTypes._POINTERTAP = 0x20;
  1345. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1346. return PointerEventTypes;
  1347. }());
  1348. BABYLON.PointerEventTypes = PointerEventTypes;
  1349. var PointerInfoBase = /** @class */ (function () {
  1350. function PointerInfoBase(type, event) {
  1351. this.type = type;
  1352. this.event = event;
  1353. }
  1354. return PointerInfoBase;
  1355. }());
  1356. BABYLON.PointerInfoBase = PointerInfoBase;
  1357. /**
  1358. * This class is used to store pointer related info for the onPrePointerObservable event.
  1359. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1360. */
  1361. var PointerInfoPre = /** @class */ (function (_super) {
  1362. __extends(PointerInfoPre, _super);
  1363. function PointerInfoPre(type, event, localX, localY) {
  1364. var _this = _super.call(this, type, event) || this;
  1365. _this.skipOnPointerObservable = false;
  1366. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1367. return _this;
  1368. }
  1369. return PointerInfoPre;
  1370. }(PointerInfoBase));
  1371. BABYLON.PointerInfoPre = PointerInfoPre;
  1372. /**
  1373. * This type contains all the data related to a pointer event in Babylon.js.
  1374. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1375. */
  1376. var PointerInfo = /** @class */ (function (_super) {
  1377. __extends(PointerInfo, _super);
  1378. function PointerInfo(type, event, pickInfo) {
  1379. var _this = _super.call(this, type, event) || this;
  1380. _this.pickInfo = pickInfo;
  1381. return _this;
  1382. }
  1383. return PointerInfo;
  1384. }(PointerInfoBase));
  1385. BABYLON.PointerInfo = PointerInfo;
  1386. })(BABYLON || (BABYLON = {}));
  1387. //# sourceMappingURL=babylon.pointerEvents.js.map
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the passed ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the passed ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3.
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3.
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Clamps the rgb values by the min and max values and stores the result into "result"
  1548. * @param min defines minimum clamping value (default is 0)
  1549. * @param max defines maximum clamping value (default is 1)
  1550. * @param result defines color to store the result into
  1551. * @returns the original Color3
  1552. */
  1553. Color3.prototype.clampToRef = function (min, max, result) {
  1554. if (min === void 0) { min = 0; }
  1555. if (max === void 0) { max = 1; }
  1556. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1557. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1558. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1559. return this;
  1560. };
  1561. /**
  1562. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1563. * @param otherColor defines the second operand
  1564. * @returns the new Color3
  1565. */
  1566. Color3.prototype.add = function (otherColor) {
  1567. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1568. };
  1569. /**
  1570. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1571. * @param otherColor defines the second operand
  1572. * @param result defines Color3 object to store the result into
  1573. * @returns the unmodified current Color3
  1574. */
  1575. Color3.prototype.addToRef = function (otherColor, result) {
  1576. result.r = this.r + otherColor.r;
  1577. result.g = this.g + otherColor.g;
  1578. result.b = this.b + otherColor.b;
  1579. return this;
  1580. };
  1581. /**
  1582. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1583. * @param otherColor defines the second operand
  1584. * @returns the new Color3
  1585. */
  1586. Color3.prototype.subtract = function (otherColor) {
  1587. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1588. };
  1589. /**
  1590. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1591. * @param otherColor defines the second operand
  1592. * @param result defines Color3 object to store the result into
  1593. * @returns the unmodified current Color3
  1594. */
  1595. Color3.prototype.subtractToRef = function (otherColor, result) {
  1596. result.r = this.r - otherColor.r;
  1597. result.g = this.g - otherColor.g;
  1598. result.b = this.b - otherColor.b;
  1599. return this;
  1600. };
  1601. /**
  1602. * Copy the current object
  1603. * @returns a new Color3 copied the current one
  1604. */
  1605. Color3.prototype.clone = function () {
  1606. return new Color3(this.r, this.g, this.b);
  1607. };
  1608. /**
  1609. * Copies the rgb values from the source in the current Color3
  1610. * @param source defines the source Color3 object
  1611. * @returns the updated Color3 object
  1612. */
  1613. Color3.prototype.copyFrom = function (source) {
  1614. this.r = source.r;
  1615. this.g = source.g;
  1616. this.b = source.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Updates the Color3 rgb values from the passed floats
  1621. * @param r defines the red component to read from
  1622. * @param g defines the green component to read from
  1623. * @param b defines the blue component to read from
  1624. * @returns the current Color3 object
  1625. */
  1626. Color3.prototype.copyFromFloats = function (r, g, b) {
  1627. this.r = r;
  1628. this.g = g;
  1629. this.b = b;
  1630. return this;
  1631. };
  1632. /**
  1633. * Updates the Color3 rgb values from the passed floats
  1634. * @param r defines the red component to read from
  1635. * @param g defines the green component to read from
  1636. * @param b defines the blue component to read from
  1637. * @returns the current Color3 object
  1638. */
  1639. Color3.prototype.set = function (r, g, b) {
  1640. return this.copyFromFloats(r, g, b);
  1641. };
  1642. /**
  1643. * Compute the Color3 hexadecimal code as a string
  1644. * @returns a string containing the hexadecimal representation of the Color3 object
  1645. */
  1646. Color3.prototype.toHexString = function () {
  1647. var intR = (this.r * 255) | 0;
  1648. var intG = (this.g * 255) | 0;
  1649. var intB = (this.b * 255) | 0;
  1650. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1651. };
  1652. /**
  1653. * Computes a new Color3 converted from the current one to linear space
  1654. * @returns a new Color3 object
  1655. */
  1656. Color3.prototype.toLinearSpace = function () {
  1657. var convertedColor = new Color3();
  1658. this.toLinearSpaceToRef(convertedColor);
  1659. return convertedColor;
  1660. };
  1661. /**
  1662. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1663. * @param convertedColor defines the Color3 object where to store the linear space version
  1664. * @returns the unmodified Color3
  1665. */
  1666. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1667. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1668. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1669. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1670. return this;
  1671. };
  1672. /**
  1673. * Computes a new Color3 converted from the current one to gamma space
  1674. * @returns a new Color3 object
  1675. */
  1676. Color3.prototype.toGammaSpace = function () {
  1677. var convertedColor = new Color3();
  1678. this.toGammaSpaceToRef(convertedColor);
  1679. return convertedColor;
  1680. };
  1681. /**
  1682. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1683. * @param convertedColor defines the Color3 object where to store the gamma space version
  1684. * @returns the unmodified Color3
  1685. */
  1686. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1687. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1688. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1689. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1690. return this;
  1691. };
  1692. // Statics
  1693. /**
  1694. * Creates a new Color3 from the string containing valid hexadecimal values
  1695. * @param hex defines a string containing valid hexadecimal values
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromHexString = function (hex) {
  1699. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1700. return new Color3(0, 0, 0);
  1701. }
  1702. var r = parseInt(hex.substring(1, 3), 16);
  1703. var g = parseInt(hex.substring(3, 5), 16);
  1704. var b = parseInt(hex.substring(5, 7), 16);
  1705. return Color3.FromInts(r, g, b);
  1706. };
  1707. /**
  1708. * Creates a new Vector3 from the starting index of the passed array
  1709. * @param array defines the source array
  1710. * @param offset defines an offset in the source array
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.FromArray = function (array, offset) {
  1714. if (offset === void 0) { offset = 0; }
  1715. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1716. };
  1717. /**
  1718. * Creates a new Color3 from integer values (< 256)
  1719. * @param r defines the red component to read from (value between 0 and 255)
  1720. * @param g defines the green component to read from (value between 0 and 255)
  1721. * @param b defines the blue component to read from (value between 0 and 255)
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.FromInts = function (r, g, b) {
  1725. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1726. };
  1727. /**
  1728. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1729. * @param start defines the start Color3 value
  1730. * @param end defines the end Color3 value
  1731. * @param amount defines the gradient value between start and end
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Lerp = function (start, end, amount) {
  1735. var r = start.r + ((end.r - start.r) * amount);
  1736. var g = start.g + ((end.g - start.g) * amount);
  1737. var b = start.b + ((end.b - start.b) * amount);
  1738. return new Color3(r, g, b);
  1739. };
  1740. /**
  1741. * Returns a Color3 value containing a red color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Red = function () { return new Color3(1, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a green color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Green = function () { return new Color3(0, 1, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a blue color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a black color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Black = function () { return new Color3(0, 0, 0); };
  1760. /**
  1761. * Returns a Color3 value containing a white color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.White = function () { return new Color3(1, 1, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a purple color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a magenta color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1775. /**
  1776. * Returns a Color3 value containing a yellow color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1780. /**
  1781. * Returns a Color3 value containing a gray color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1785. /**
  1786. * Returns a Color3 value containing a teal color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1790. /**
  1791. * Returns a Color3 value containing a random color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1795. return Color3;
  1796. }());
  1797. BABYLON.Color3 = Color3;
  1798. /**
  1799. * Class used to hold a RBGA color
  1800. */
  1801. var Color4 = /** @class */ (function () {
  1802. /**
  1803. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1804. * @param r defines the red component (between 0 and 1, default is 0)
  1805. * @param g defines the green component (between 0 and 1, default is 0)
  1806. * @param b defines the blue component (between 0 and 1, default is 0)
  1807. * @param a defines the alpha component (between 0 and 1, default is 1)
  1808. */
  1809. function Color4(
  1810. /**
  1811. * Defines the red component (between 0 and 1, default is 0)
  1812. */
  1813. r,
  1814. /**
  1815. * Defines the green component (between 0 and 1, default is 0)
  1816. */
  1817. g,
  1818. /**
  1819. * Defines the blue component (between 0 and 1, default is 0)
  1820. */
  1821. b,
  1822. /**
  1823. * Defines the alpha component (between 0 and 1, default is 1)
  1824. */
  1825. a) {
  1826. if (r === void 0) { r = 0; }
  1827. if (g === void 0) { g = 0; }
  1828. if (b === void 0) { b = 0; }
  1829. if (a === void 0) { a = 1; }
  1830. this.r = r;
  1831. this.g = g;
  1832. this.b = b;
  1833. this.a = a;
  1834. }
  1835. // Operators
  1836. /**
  1837. * Adds in place the passed Color4 values to the current Color4 object
  1838. * @param right defines the second operand
  1839. * @returns the current updated Color4 object
  1840. */
  1841. Color4.prototype.addInPlace = function (right) {
  1842. this.r += right.r;
  1843. this.g += right.g;
  1844. this.b += right.b;
  1845. this.a += right.a;
  1846. return this;
  1847. };
  1848. /**
  1849. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1850. * @returns the new array
  1851. */
  1852. Color4.prototype.asArray = function () {
  1853. var result = new Array();
  1854. this.toArray(result, 0);
  1855. return result;
  1856. };
  1857. /**
  1858. * Stores from the starting index in the passed array the Color4 successive values
  1859. * @param array defines the array where to store the r,g,b components
  1860. * @param index defines an optional index in the target array to define where to start storing values
  1861. * @returns the current Color4 object
  1862. */
  1863. Color4.prototype.toArray = function (array, index) {
  1864. if (index === undefined) {
  1865. index = 0;
  1866. }
  1867. array[index] = this.r;
  1868. array[index + 1] = this.g;
  1869. array[index + 2] = this.b;
  1870. array[index + 3] = this.a;
  1871. return this;
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.add = function (right) {
  1879. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1880. };
  1881. /**
  1882. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1883. * @param right defines the second operand
  1884. * @returns a new Color4 object
  1885. */
  1886. Color4.prototype.subtract = function (right) {
  1887. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1888. };
  1889. /**
  1890. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1891. * @param right defines the second operand
  1892. * @param result defines the Color4 object where to store the result
  1893. * @returns the current Color4 object
  1894. */
  1895. Color4.prototype.subtractToRef = function (right, result) {
  1896. result.r = this.r - right.r;
  1897. result.g = this.g - right.g;
  1898. result.b = this.b - right.b;
  1899. result.a = this.a - right.a;
  1900. return this;
  1901. };
  1902. /**
  1903. * Creates a new Color4 with the current Color4 values multiplied by scale
  1904. * @param scale defines the scaling factor to apply
  1905. * @returns a new Color4 object
  1906. */
  1907. Color4.prototype.scale = function (scale) {
  1908. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1909. };
  1910. /**
  1911. * Multiplies the current Color4 values by scale and stores the result in "result"
  1912. * @param scale defines the scaling factor to apply
  1913. * @param result defines the Color4 object where to store the result
  1914. * @returns the current Color4.
  1915. */
  1916. Color4.prototype.scaleToRef = function (scale, result) {
  1917. result.r = this.r * scale;
  1918. result.g = this.g * scale;
  1919. result.b = this.b * scale;
  1920. result.a = this.a * scale;
  1921. return this;
  1922. };
  1923. /**
  1924. * Clamps the rgb values by the min and max values and stores the result into "result"
  1925. * @param min defines minimum clamping value (default is 0)
  1926. * @param max defines maximum clamping value (default is 1)
  1927. * @param result defines color to store the result into.
  1928. * @returns the cuurent Color4
  1929. */
  1930. Color4.prototype.clampToRef = function (min, max, result) {
  1931. if (min === void 0) { min = 0; }
  1932. if (max === void 0) { max = 1; }
  1933. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1934. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1935. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1936. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1937. return this;
  1938. };
  1939. /**
  1940. * Multipy an Color4 value by another and return a new Color4 object
  1941. * @param color defines the Color4 value to multiply by
  1942. * @returns a new Color4 object
  1943. */
  1944. Color4.prototype.multiply = function (color) {
  1945. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1946. };
  1947. /**
  1948. * Multipy a Color4 value by another and push the result in a reference value
  1949. * @param color defines the Color4 value to multiply by
  1950. * @param result defines the Color4 to fill the result in
  1951. * @returns the result Color4
  1952. */
  1953. Color4.prototype.multiplyToRef = function (color, result) {
  1954. result.r = this.r * color.r;
  1955. result.g = this.g * color.g;
  1956. result.b = this.b * color.b;
  1957. result.a = this.a * color.a;
  1958. return result;
  1959. };
  1960. /**
  1961. * Creates a string with the Color4 current values
  1962. * @returns the string representation of the Color4 object
  1963. */
  1964. Color4.prototype.toString = function () {
  1965. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1966. };
  1967. /**
  1968. * Returns the string "Color4"
  1969. * @returns "Color4"
  1970. */
  1971. Color4.prototype.getClassName = function () {
  1972. return "Color4";
  1973. };
  1974. /**
  1975. * Compute the Color4 hash code
  1976. * @returns an unique number that can be used to hash Color4 objects
  1977. */
  1978. Color4.prototype.getHashCode = function () {
  1979. var hash = this.r || 0;
  1980. hash = (hash * 397) ^ (this.g || 0);
  1981. hash = (hash * 397) ^ (this.b || 0);
  1982. hash = (hash * 397) ^ (this.a || 0);
  1983. return hash;
  1984. };
  1985. /**
  1986. * Creates a new Color4 copied from the current one
  1987. * @returns a new Color4 object
  1988. */
  1989. Color4.prototype.clone = function () {
  1990. return new Color4(this.r, this.g, this.b, this.a);
  1991. };
  1992. /**
  1993. * Copies the passed Color4 values into the current one
  1994. * @param source defines the source Color4 object
  1995. * @returns the current updated Color4 object
  1996. */
  1997. Color4.prototype.copyFrom = function (source) {
  1998. this.r = source.r;
  1999. this.g = source.g;
  2000. this.b = source.b;
  2001. this.a = source.a;
  2002. return this;
  2003. };
  2004. /**
  2005. * Copies the passed float values into the current one
  2006. * @param r defines the red component to read from
  2007. * @param g defines the green component to read from
  2008. * @param b defines the blue component to read from
  2009. * @param a defines the alpha component to read from
  2010. * @returns the current updated Color4 object
  2011. */
  2012. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2013. this.r = r;
  2014. this.g = g;
  2015. this.b = b;
  2016. this.a = a;
  2017. return this;
  2018. };
  2019. /**
  2020. * Copies the passed float values into the current one
  2021. * @param r defines the red component to read from
  2022. * @param g defines the green component to read from
  2023. * @param b defines the blue component to read from
  2024. * @param a defines the alpha component to read from
  2025. * @returns the current updated Color4 object
  2026. */
  2027. Color4.prototype.set = function (r, g, b, a) {
  2028. return this.copyFromFloats(r, g, b, a);
  2029. };
  2030. /**
  2031. * Compute the Color4 hexadecimal code as a string
  2032. * @returns a string containing the hexadecimal representation of the Color4 object
  2033. */
  2034. Color4.prototype.toHexString = function () {
  2035. var intR = (this.r * 255) | 0;
  2036. var intG = (this.g * 255) | 0;
  2037. var intB = (this.b * 255) | 0;
  2038. var intA = (this.a * 255) | 0;
  2039. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2040. };
  2041. /**
  2042. * Computes a new Color4 converted from the current one to linear space
  2043. * @returns a new Color4 object
  2044. */
  2045. Color4.prototype.toLinearSpace = function () {
  2046. var convertedColor = new Color4();
  2047. this.toLinearSpaceToRef(convertedColor);
  2048. return convertedColor;
  2049. };
  2050. /**
  2051. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2052. * @param convertedColor defines the Color4 object where to store the linear space version
  2053. * @returns the unmodified Color4
  2054. */
  2055. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2056. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2057. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2058. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2059. convertedColor.a = this.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Computes a new Color4 converted from the current one to gamma space
  2064. * @returns a new Color4 object
  2065. */
  2066. Color4.prototype.toGammaSpace = function () {
  2067. var convertedColor = new Color4();
  2068. this.toGammaSpaceToRef(convertedColor);
  2069. return convertedColor;
  2070. };
  2071. /**
  2072. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2073. * @param convertedColor defines the Color4 object where to store the gamma space version
  2074. * @returns the unmodified Color4
  2075. */
  2076. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2077. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2078. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2079. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2080. convertedColor.a = this.a;
  2081. return this;
  2082. };
  2083. // Statics
  2084. /**
  2085. * Creates a new Color4 from the string containing valid hexadecimal values
  2086. * @param hex defines a string containing valid hexadecimal values
  2087. * @returns a new Color4 object
  2088. */
  2089. Color4.FromHexString = function (hex) {
  2090. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2091. return new Color4(0.0, 0.0, 0.0, 0.0);
  2092. }
  2093. var r = parseInt(hex.substring(1, 3), 16);
  2094. var g = parseInt(hex.substring(3, 5), 16);
  2095. var b = parseInt(hex.substring(5, 7), 16);
  2096. var a = parseInt(hex.substring(7, 9), 16);
  2097. return Color4.FromInts(r, g, b, a);
  2098. };
  2099. /**
  2100. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2101. * @param left defines the start value
  2102. * @param right defines the end value
  2103. * @param amount defines the gradient factor
  2104. * @returns a new Color4 object
  2105. */
  2106. Color4.Lerp = function (left, right, amount) {
  2107. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2108. Color4.LerpToRef(left, right, amount, result);
  2109. return result;
  2110. };
  2111. /**
  2112. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2113. * @param left defines the start value
  2114. * @param right defines the end value
  2115. * @param amount defines the gradient factor
  2116. * @param result defines the Color4 object where to store data
  2117. */
  2118. Color4.LerpToRef = function (left, right, amount, result) {
  2119. result.r = left.r + (right.r - left.r) * amount;
  2120. result.g = left.g + (right.g - left.g) * amount;
  2121. result.b = left.b + (right.b - left.b) * amount;
  2122. result.a = left.a + (right.a - left.a) * amount;
  2123. };
  2124. /**
  2125. * Creates a new Color4 from the starting index element of the passed array
  2126. * @param array defines the source array to read from
  2127. * @param offset defines the offset in the source array
  2128. * @returns a new Color4 object
  2129. */
  2130. Color4.FromArray = function (array, offset) {
  2131. if (offset === void 0) { offset = 0; }
  2132. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2133. };
  2134. /**
  2135. * Creates a new Color3 from integer values (< 256)
  2136. * @param r defines the red component to read from (value between 0 and 255)
  2137. * @param g defines the green component to read from (value between 0 and 255)
  2138. * @param b defines the blue component to read from (value between 0 and 255)
  2139. * @param a defines the alpha component to read from (value between 0 and 255)
  2140. * @returns a new Color3 object
  2141. */
  2142. Color4.FromInts = function (r, g, b, a) {
  2143. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2144. };
  2145. /**
  2146. * Check the content of a given array and convert it to an array containing RGBA data
  2147. * If the original array was already containing count * 4 values then it is returned directly
  2148. * @param colors defines the array to check
  2149. * @param count defines the number of RGBA data to expect
  2150. * @returns an array containing count * 4 values (RGBA)
  2151. */
  2152. Color4.CheckColors4 = function (colors, count) {
  2153. // Check if color3 was used
  2154. if (colors.length === count * 3) {
  2155. var colors4 = [];
  2156. for (var index = 0; index < colors.length; index += 3) {
  2157. var newIndex = (index / 3) * 4;
  2158. colors4[newIndex] = colors[index];
  2159. colors4[newIndex + 1] = colors[index + 1];
  2160. colors4[newIndex + 2] = colors[index + 2];
  2161. colors4[newIndex + 3] = 1.0;
  2162. }
  2163. return colors4;
  2164. }
  2165. return colors;
  2166. };
  2167. return Color4;
  2168. }());
  2169. BABYLON.Color4 = Color4;
  2170. var Vector2 = /** @class */ (function () {
  2171. /**
  2172. * Creates a new Vector2 from the passed x and y coordinates.
  2173. */
  2174. function Vector2(x, y) {
  2175. this.x = x;
  2176. this.y = y;
  2177. }
  2178. /**
  2179. * Returns a string with the Vector2 coordinates.
  2180. */
  2181. Vector2.prototype.toString = function () {
  2182. return "{X: " + this.x + " Y:" + this.y + "}";
  2183. };
  2184. /**
  2185. * Returns the string "Vector2"
  2186. */
  2187. Vector2.prototype.getClassName = function () {
  2188. return "Vector2";
  2189. };
  2190. /**
  2191. * Returns the Vector2 hash code as a number.
  2192. */
  2193. Vector2.prototype.getHashCode = function () {
  2194. var hash = this.x || 0;
  2195. hash = (hash * 397) ^ (this.y || 0);
  2196. return hash;
  2197. };
  2198. // Operators
  2199. /**
  2200. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2201. * Returns the Vector2.
  2202. */
  2203. Vector2.prototype.toArray = function (array, index) {
  2204. if (index === void 0) { index = 0; }
  2205. array[index] = this.x;
  2206. array[index + 1] = this.y;
  2207. return this;
  2208. };
  2209. /**
  2210. * Returns a new array with 2 elements : the Vector2 coordinates.
  2211. */
  2212. Vector2.prototype.asArray = function () {
  2213. var result = new Array();
  2214. this.toArray(result, 0);
  2215. return result;
  2216. };
  2217. /**
  2218. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2219. * Returns the updated Vector2.
  2220. */
  2221. Vector2.prototype.copyFrom = function (source) {
  2222. this.x = source.x;
  2223. this.y = source.y;
  2224. return this;
  2225. };
  2226. /**
  2227. * Sets the Vector2 coordinates with the passed floats.
  2228. * Returns the updated Vector2.
  2229. */
  2230. Vector2.prototype.copyFromFloats = function (x, y) {
  2231. this.x = x;
  2232. this.y = y;
  2233. return this;
  2234. };
  2235. /**
  2236. * Sets the Vector2 coordinates with the passed floats.
  2237. * Returns the updated Vector2.
  2238. */
  2239. Vector2.prototype.set = function (x, y) {
  2240. return this.copyFromFloats(x, y);
  2241. };
  2242. /**
  2243. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2244. */
  2245. Vector2.prototype.add = function (otherVector) {
  2246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2247. };
  2248. /**
  2249. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2250. * Returns the Vector2.
  2251. */
  2252. Vector2.prototype.addToRef = function (otherVector, result) {
  2253. result.x = this.x + otherVector.x;
  2254. result.y = this.y + otherVector.y;
  2255. return this;
  2256. };
  2257. /**
  2258. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2259. * Returns the updated Vector2.
  2260. */
  2261. Vector2.prototype.addInPlace = function (otherVector) {
  2262. this.x += otherVector.x;
  2263. this.y += otherVector.y;
  2264. return this;
  2265. };
  2266. /**
  2267. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2268. */
  2269. Vector2.prototype.addVector3 = function (otherVector) {
  2270. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2271. };
  2272. /**
  2273. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2274. */
  2275. Vector2.prototype.subtract = function (otherVector) {
  2276. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2277. };
  2278. /**
  2279. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2280. * Returns the Vector2.
  2281. */
  2282. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2283. result.x = this.x - otherVector.x;
  2284. result.y = this.y - otherVector.y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2289. * Returns the updated Vector2.
  2290. */
  2291. Vector2.prototype.subtractInPlace = function (otherVector) {
  2292. this.x -= otherVector.x;
  2293. this.y -= otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2298. * Returns the updated Vector2.
  2299. */
  2300. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2301. this.x *= otherVector.x;
  2302. this.y *= otherVector.y;
  2303. return this;
  2304. };
  2305. /**
  2306. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2307. */
  2308. Vector2.prototype.multiply = function (otherVector) {
  2309. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2310. };
  2311. /**
  2312. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2313. * Returns the Vector2.
  2314. */
  2315. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2316. result.x = this.x * otherVector.x;
  2317. result.y = this.y * otherVector.y;
  2318. return this;
  2319. };
  2320. /**
  2321. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2322. */
  2323. Vector2.prototype.multiplyByFloats = function (x, y) {
  2324. return new Vector2(this.x * x, this.y * y);
  2325. };
  2326. /**
  2327. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2328. */
  2329. Vector2.prototype.divide = function (otherVector) {
  2330. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2331. };
  2332. /**
  2333. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2334. * Returns the Vector2.
  2335. */
  2336. Vector2.prototype.divideToRef = function (otherVector, result) {
  2337. result.x = this.x / otherVector.x;
  2338. result.y = this.y / otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Divides the current Vector3 coordinates by the passed ones.
  2343. * Returns the updated Vector3.
  2344. */
  2345. Vector2.prototype.divideInPlace = function (otherVector) {
  2346. return this.divideToRef(otherVector, this);
  2347. };
  2348. /**
  2349. * Returns a new Vector2 with current Vector2 negated coordinates.
  2350. */
  2351. Vector2.prototype.negate = function () {
  2352. return new Vector2(-this.x, -this.y);
  2353. };
  2354. /**
  2355. * Multiply the Vector2 coordinates by scale.
  2356. * Returns the updated Vector2.
  2357. */
  2358. Vector2.prototype.scaleInPlace = function (scale) {
  2359. this.x *= scale;
  2360. this.y *= scale;
  2361. return this;
  2362. };
  2363. /**
  2364. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2365. */
  2366. Vector2.prototype.scale = function (scale) {
  2367. return new Vector2(this.x * scale, this.y * scale);
  2368. };
  2369. /**
  2370. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2371. */
  2372. Vector2.prototype.equals = function (otherVector) {
  2373. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2374. };
  2375. /**
  2376. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2377. */
  2378. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2379. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2380. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2381. };
  2382. // Properties
  2383. /**
  2384. * Returns the vector length (float).
  2385. */
  2386. Vector2.prototype.length = function () {
  2387. return Math.sqrt(this.x * this.x + this.y * this.y);
  2388. };
  2389. /**
  2390. * Returns the vector squared length (float);
  2391. */
  2392. Vector2.prototype.lengthSquared = function () {
  2393. return (this.x * this.x + this.y * this.y);
  2394. };
  2395. // Methods
  2396. /**
  2397. * Normalize the vector.
  2398. * Returns the updated Vector2.
  2399. */
  2400. Vector2.prototype.normalize = function () {
  2401. var len = this.length();
  2402. if (len === 0)
  2403. return this;
  2404. var num = 1.0 / len;
  2405. this.x *= num;
  2406. this.y *= num;
  2407. return this;
  2408. };
  2409. /**
  2410. * Returns a new Vector2 copied from the Vector2.
  2411. */
  2412. Vector2.prototype.clone = function () {
  2413. return new Vector2(this.x, this.y);
  2414. };
  2415. // Statics
  2416. /**
  2417. * Returns a new Vector2(0, 0)
  2418. */
  2419. Vector2.Zero = function () {
  2420. return new Vector2(0, 0);
  2421. };
  2422. /**
  2423. * Returns a new Vector2(1, 1)
  2424. */
  2425. Vector2.One = function () {
  2426. return new Vector2(1, 1);
  2427. };
  2428. /**
  2429. * Returns a new Vector2 set from the passed index element of the passed array.
  2430. */
  2431. Vector2.FromArray = function (array, offset) {
  2432. if (offset === void 0) { offset = 0; }
  2433. return new Vector2(array[offset], array[offset + 1]);
  2434. };
  2435. /**
  2436. * Sets "result" from the passed index element of the passed array.
  2437. */
  2438. Vector2.FromArrayToRef = function (array, offset, result) {
  2439. result.x = array[offset];
  2440. result.y = array[offset + 1];
  2441. };
  2442. /**
  2443. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2444. */
  2445. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2446. var squared = amount * amount;
  2447. var cubed = amount * squared;
  2448. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2449. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2450. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2451. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2452. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2453. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2454. return new Vector2(x, y);
  2455. };
  2456. /**
  2457. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2458. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2459. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2460. */
  2461. Vector2.Clamp = function (value, min, max) {
  2462. var x = value.x;
  2463. x = (x > max.x) ? max.x : x;
  2464. x = (x < min.x) ? min.x : x;
  2465. var y = value.y;
  2466. y = (y > max.y) ? max.y : y;
  2467. y = (y < min.y) ? min.y : y;
  2468. return new Vector2(x, y);
  2469. };
  2470. /**
  2471. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2472. */
  2473. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2474. var squared = amount * amount;
  2475. var cubed = amount * squared;
  2476. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2477. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2478. var part3 = (cubed - (2.0 * squared)) + amount;
  2479. var part4 = cubed - squared;
  2480. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2481. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2482. return new Vector2(x, y);
  2483. };
  2484. /**
  2485. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2486. */
  2487. Vector2.Lerp = function (start, end, amount) {
  2488. var x = start.x + ((end.x - start.x) * amount);
  2489. var y = start.y + ((end.y - start.y) * amount);
  2490. return new Vector2(x, y);
  2491. };
  2492. /**
  2493. * Returns the dot product (float) of the vector "left" and the vector "right".
  2494. */
  2495. Vector2.Dot = function (left, right) {
  2496. return left.x * right.x + left.y * right.y;
  2497. };
  2498. /**
  2499. * Returns a new Vector2 equal to the normalized passed vector.
  2500. */
  2501. Vector2.Normalize = function (vector) {
  2502. var newVector = vector.clone();
  2503. newVector.normalize();
  2504. return newVector;
  2505. };
  2506. /**
  2507. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2508. */
  2509. Vector2.Minimize = function (left, right) {
  2510. var x = (left.x < right.x) ? left.x : right.x;
  2511. var y = (left.y < right.y) ? left.y : right.y;
  2512. return new Vector2(x, y);
  2513. };
  2514. /**
  2515. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2516. */
  2517. Vector2.Maximize = function (left, right) {
  2518. var x = (left.x > right.x) ? left.x : right.x;
  2519. var y = (left.y > right.y) ? left.y : right.y;
  2520. return new Vector2(x, y);
  2521. };
  2522. /**
  2523. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2524. */
  2525. Vector2.Transform = function (vector, transformation) {
  2526. var r = Vector2.Zero();
  2527. Vector2.TransformToRef(vector, transformation, r);
  2528. return r;
  2529. };
  2530. /**
  2531. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2532. */
  2533. Vector2.TransformToRef = function (vector, transformation, result) {
  2534. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2535. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2536. result.x = x;
  2537. result.y = y;
  2538. };
  2539. /**
  2540. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2541. */
  2542. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2543. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2544. var sign = a < 0 ? -1 : 1;
  2545. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2546. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2547. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2548. };
  2549. /**
  2550. * Returns the distance (float) between the vectors "value1" and "value2".
  2551. */
  2552. Vector2.Distance = function (value1, value2) {
  2553. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2554. };
  2555. /**
  2556. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2557. */
  2558. Vector2.DistanceSquared = function (value1, value2) {
  2559. var x = value1.x - value2.x;
  2560. var y = value1.y - value2.y;
  2561. return (x * x) + (y * y);
  2562. };
  2563. /**
  2564. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2565. */
  2566. Vector2.Center = function (value1, value2) {
  2567. var center = value1.add(value2);
  2568. center.scaleInPlace(0.5);
  2569. return center;
  2570. };
  2571. /**
  2572. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2573. */
  2574. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2575. var l2 = Vector2.DistanceSquared(segA, segB);
  2576. if (l2 === 0.0) {
  2577. return Vector2.Distance(p, segA);
  2578. }
  2579. var v = segB.subtract(segA);
  2580. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2581. var proj = segA.add(v.multiplyByFloats(t, t));
  2582. return Vector2.Distance(p, proj);
  2583. };
  2584. return Vector2;
  2585. }());
  2586. BABYLON.Vector2 = Vector2;
  2587. /**
  2588. * Classed used to store (x,y,z) vector representation
  2589. * A Vector3 is the main object used in 3D geometry
  2590. * It can represent etiher the coordinates of a point the space, either a direction
  2591. * Reminder: Babylon.js uses a left handed forward facing system
  2592. */
  2593. var Vector3 = /** @class */ (function () {
  2594. /**
  2595. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2596. * @param x defines the first coordinates (on X axis)
  2597. * @param y defines the second coordinates (on Y axis)
  2598. * @param z defines the third coordinates (on Z axis)
  2599. */
  2600. function Vector3(
  2601. /**
  2602. * Defines the first coordinates (on X axis)
  2603. */
  2604. x,
  2605. /**
  2606. * Defines the second coordinates (on Y axis)
  2607. */
  2608. y,
  2609. /**
  2610. * Defines the third coordinates (on Z axis)
  2611. */
  2612. z) {
  2613. this.x = x;
  2614. this.y = y;
  2615. this.z = z;
  2616. }
  2617. /**
  2618. * Creates a string representation of the Vector3
  2619. * @returns a string with the Vector3 coordinates.
  2620. */
  2621. Vector3.prototype.toString = function () {
  2622. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2623. };
  2624. /**
  2625. * Gets the class name
  2626. * @returns the string "Vector3"
  2627. */
  2628. Vector3.prototype.getClassName = function () {
  2629. return "Vector3";
  2630. };
  2631. /**
  2632. * Creates the Vector3 hash code
  2633. * @returns a number which tends to be unique between Vector3 instances
  2634. */
  2635. Vector3.prototype.getHashCode = function () {
  2636. var hash = this.x || 0;
  2637. hash = (hash * 397) ^ (this.y || 0);
  2638. hash = (hash * 397) ^ (this.z || 0);
  2639. return hash;
  2640. };
  2641. // Operators
  2642. /**
  2643. * Creates an array containing three elements : the coordinates of the Vector3
  2644. * @returns a new array of numbers
  2645. */
  2646. Vector3.prototype.asArray = function () {
  2647. var result = [];
  2648. this.toArray(result, 0);
  2649. return result;
  2650. };
  2651. /**
  2652. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2653. * @param array defines the destination array
  2654. * @param index defines the offset in the destination array
  2655. * @returns the current Vector3
  2656. */
  2657. Vector3.prototype.toArray = function (array, index) {
  2658. if (index === void 0) { index = 0; }
  2659. array[index] = this.x;
  2660. array[index + 1] = this.y;
  2661. array[index + 2] = this.z;
  2662. return this;
  2663. };
  2664. /**
  2665. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2666. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2667. */
  2668. Vector3.prototype.toQuaternion = function () {
  2669. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2670. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2671. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2672. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2673. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2674. var cosy = Math.cos(this.y * 0.5);
  2675. var siny = Math.sin(this.y * 0.5);
  2676. result.x = coszMinusx * siny;
  2677. result.y = -sinzMinusx * siny;
  2678. result.z = sinxPlusz * cosy;
  2679. result.w = cosxPlusz * cosy;
  2680. return result;
  2681. };
  2682. /**
  2683. * Adds the passed vector to the current Vector3
  2684. * @param otherVector defines the second operand
  2685. * @returns the current updated Vector3
  2686. */
  2687. Vector3.prototype.addInPlace = function (otherVector) {
  2688. this.x += otherVector.x;
  2689. this.y += otherVector.y;
  2690. this.z += otherVector.z;
  2691. return this;
  2692. };
  2693. /**
  2694. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2695. * @param otherVector defines the second operand
  2696. * @returns the resulting Vector3
  2697. */
  2698. Vector3.prototype.add = function (otherVector) {
  2699. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2700. };
  2701. /**
  2702. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2703. * @param otherVector defines the second operand
  2704. * @param result defines the Vector3 object where to store the result
  2705. * @returns the current Vector3
  2706. */
  2707. Vector3.prototype.addToRef = function (otherVector, result) {
  2708. result.x = this.x + otherVector.x;
  2709. result.y = this.y + otherVector.y;
  2710. result.z = this.z + otherVector.z;
  2711. return this;
  2712. };
  2713. /**
  2714. * Subtract the passed vector from the current Vector3
  2715. * @param otherVector defines the second operand
  2716. * @returns the current updated Vector3
  2717. */
  2718. Vector3.prototype.subtractInPlace = function (otherVector) {
  2719. this.x -= otherVector.x;
  2720. this.y -= otherVector.y;
  2721. this.z -= otherVector.z;
  2722. return this;
  2723. };
  2724. /**
  2725. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2726. * @param otherVector defines the second operand
  2727. * @returns the resulting Vector3
  2728. */
  2729. Vector3.prototype.subtract = function (otherVector) {
  2730. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2731. };
  2732. /**
  2733. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2734. * @param otherVector defines the second operand
  2735. * @param result defines the Vector3 object where to store the result
  2736. * @returns the current Vector3
  2737. */
  2738. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2739. result.x = this.x - otherVector.x;
  2740. result.y = this.y - otherVector.y;
  2741. result.z = this.z - otherVector.z;
  2742. return this;
  2743. };
  2744. /**
  2745. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2746. * @param x defines the x coordinate of the operand
  2747. * @param y defines the y coordinate of the operand
  2748. * @param z defines the z coordinate of the operand
  2749. * @returns the resulting Vector3
  2750. */
  2751. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2752. return new Vector3(this.x - x, this.y - y, this.z - z);
  2753. };
  2754. /**
  2755. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2756. * @param x defines the x coordinate of the operand
  2757. * @param y defines the y coordinate of the operand
  2758. * @param z defines the z coordinate of the operand
  2759. * @param result defines the Vector3 object where to store the result
  2760. * @returns the current Vector3
  2761. */
  2762. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2763. result.x = this.x - x;
  2764. result.y = this.y - y;
  2765. result.z = this.z - z;
  2766. return this;
  2767. };
  2768. /**
  2769. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2770. * @returns a new Vector3
  2771. */
  2772. Vector3.prototype.negate = function () {
  2773. return new Vector3(-this.x, -this.y, -this.z);
  2774. };
  2775. /**
  2776. * Multiplies the Vector3 coordinates by the float "scale"
  2777. * @param scale defines the multiplier factor
  2778. * @returns the current updated Vector3
  2779. */
  2780. Vector3.prototype.scaleInPlace = function (scale) {
  2781. this.x *= scale;
  2782. this.y *= scale;
  2783. this.z *= scale;
  2784. return this;
  2785. };
  2786. /**
  2787. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2788. * @param scale defines the multiplier factor
  2789. * @returns a new Vector3
  2790. */
  2791. Vector3.prototype.scale = function (scale) {
  2792. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2793. };
  2794. /**
  2795. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2796. * @param scale defines the multiplier factor
  2797. * @param result defines the Vector3 object where to store the result
  2798. * @returns the current Vector3
  2799. */
  2800. Vector3.prototype.scaleToRef = function (scale, result) {
  2801. result.x = this.x * scale;
  2802. result.y = this.y * scale;
  2803. result.z = this.z * scale;
  2804. return this;
  2805. };
  2806. /**
  2807. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2808. * @param otherVector defines the second operand
  2809. * @returns true if both vectors are equals
  2810. */
  2811. Vector3.prototype.equals = function (otherVector) {
  2812. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2813. };
  2814. /**
  2815. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2816. * @param otherVector defines the second operand
  2817. * @param epsilon defines the minimal distance to define values as equals
  2818. * @returns true if both vectors are distant less than epsilon
  2819. */
  2820. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2821. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2822. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2823. };
  2824. /**
  2825. * Returns true if the current Vector3 coordinates equals the passed floats
  2826. * @param x defines the x coordinate of the operand
  2827. * @param y defines the y coordinate of the operand
  2828. * @param z defines the z coordinate of the operand
  2829. * @returns true if both vectors are equals
  2830. */
  2831. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2832. return this.x === x && this.y === y && this.z === z;
  2833. };
  2834. /**
  2835. * Multiplies the current Vector3 coordinates by the passed ones
  2836. * @param otherVector defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2840. this.x *= otherVector.x;
  2841. this.y *= otherVector.y;
  2842. this.z *= otherVector.z;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2847. * @param otherVector defines the second operand
  2848. * @returns the new Vector3
  2849. */
  2850. Vector3.prototype.multiply = function (otherVector) {
  2851. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2852. };
  2853. /**
  2854. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2855. * @param otherVector defines the second operand
  2856. * @param result defines the Vector3 object where to store the result
  2857. * @returns the current Vector3
  2858. */
  2859. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2860. result.x = this.x * otherVector.x;
  2861. result.y = this.y * otherVector.y;
  2862. result.z = this.z * otherVector.z;
  2863. return this;
  2864. };
  2865. /**
  2866. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2867. * @param x defines the x coordinate of the operand
  2868. * @param y defines the y coordinate of the operand
  2869. * @param z defines the z coordinate of the operand
  2870. * @returns the new Vector3
  2871. */
  2872. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2873. return new Vector3(this.x * x, this.y * y, this.z * z);
  2874. };
  2875. /**
  2876. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2877. * @param otherVector defines the second operand
  2878. * @returns the new Vector3
  2879. */
  2880. Vector3.prototype.divide = function (otherVector) {
  2881. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2882. };
  2883. /**
  2884. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2885. * @param otherVector defines the second operand
  2886. * @param result defines the Vector3 object where to store the result
  2887. * @returns the current Vector3
  2888. */
  2889. Vector3.prototype.divideToRef = function (otherVector, result) {
  2890. result.x = this.x / otherVector.x;
  2891. result.y = this.y / otherVector.y;
  2892. result.z = this.z / otherVector.z;
  2893. return this;
  2894. };
  2895. /**
  2896. * Divides the current Vector3 coordinates by the passed ones.
  2897. * @param otherVector defines the second operand
  2898. * @returns the current updated Vector3
  2899. */
  2900. Vector3.prototype.divideInPlace = function (otherVector) {
  2901. return this.divideToRef(otherVector, this);
  2902. };
  2903. /**
  2904. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2905. * @param other defines the second operand
  2906. * @returns the current updated Vector3
  2907. */
  2908. Vector3.prototype.minimizeInPlace = function (other) {
  2909. if (other.x < this.x)
  2910. this.x = other.x;
  2911. if (other.y < this.y)
  2912. this.y = other.y;
  2913. if (other.z < this.z)
  2914. this.z = other.z;
  2915. return this;
  2916. };
  2917. /**
  2918. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2919. * @param other defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.maximizeInPlace = function (other) {
  2923. if (other.x > this.x)
  2924. this.x = other.x;
  2925. if (other.y > this.y)
  2926. this.y = other.y;
  2927. if (other.z > this.z)
  2928. this.z = other.z;
  2929. return this;
  2930. };
  2931. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2932. /**
  2933. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2934. */
  2935. get: function () {
  2936. var absX = Math.abs(this.x);
  2937. var absY = Math.abs(this.y);
  2938. if (absX !== absY) {
  2939. return true;
  2940. }
  2941. var absZ = Math.abs(this.z);
  2942. if (absX !== absZ) {
  2943. return true;
  2944. }
  2945. if (absY !== absZ) {
  2946. return true;
  2947. }
  2948. return false;
  2949. },
  2950. enumerable: true,
  2951. configurable: true
  2952. });
  2953. // Properties
  2954. /**
  2955. * Gets the length of the Vector3
  2956. * @returns the length of the Vecto3
  2957. */
  2958. Vector3.prototype.length = function () {
  2959. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2960. };
  2961. /**
  2962. * Gets the squared length of the Vector3
  2963. * @returns squared length of the Vector3
  2964. */
  2965. Vector3.prototype.lengthSquared = function () {
  2966. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2967. };
  2968. /**
  2969. * Normalize the current Vector3.
  2970. * Please note that this is an in place operation.
  2971. * @returns the current updated Vector3
  2972. */
  2973. Vector3.prototype.normalize = function () {
  2974. var len = this.length();
  2975. if (len === 0 || len === 1.0)
  2976. return this;
  2977. var num = 1.0 / len;
  2978. this.x *= num;
  2979. this.y *= num;
  2980. this.z *= num;
  2981. return this;
  2982. };
  2983. /**
  2984. * Normalize the current Vector3 to a new vector
  2985. * @returns the new Vector3
  2986. */
  2987. Vector3.prototype.normalizeToNew = function () {
  2988. var normalized = new Vector3(0, 0, 0);
  2989. this.normalizeToRef(normalized);
  2990. return normalized;
  2991. };
  2992. /**
  2993. * Normalize the current Vector3 to the reference
  2994. * @param reference define the Vector3 to update
  2995. * @returns the updated Vector3
  2996. */
  2997. Vector3.prototype.normalizeToRef = function (reference) {
  2998. var len = this.length();
  2999. if (len === 0 || len === 1.0) {
  3000. reference.set(this.x, this.y, this.z);
  3001. return reference;
  3002. }
  3003. var scale = 1.0 / len;
  3004. this.scaleToRef(scale, reference);
  3005. return reference;
  3006. };
  3007. /**
  3008. * Creates a new Vector3 copied from the current Vector3
  3009. * @returns the new Vector3
  3010. */
  3011. Vector3.prototype.clone = function () {
  3012. return new Vector3(this.x, this.y, this.z);
  3013. };
  3014. /**
  3015. * Copies the passed vector coordinates to the current Vector3 ones
  3016. * @param source defines the source Vector3
  3017. * @returns the current updated Vector3
  3018. */
  3019. Vector3.prototype.copyFrom = function (source) {
  3020. this.x = source.x;
  3021. this.y = source.y;
  3022. this.z = source.z;
  3023. return this;
  3024. };
  3025. /**
  3026. * Copies the passed floats to the current Vector3 coordinates
  3027. * @param x defines the x coordinate of the operand
  3028. * @param y defines the y coordinate of the operand
  3029. * @param z defines the z coordinate of the operand
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3033. this.x = x;
  3034. this.y = y;
  3035. this.z = z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Copies the passed floats to the current Vector3 coordinates
  3040. * @param x defines the x coordinate of the operand
  3041. * @param y defines the y coordinate of the operand
  3042. * @param z defines the z coordinate of the operand
  3043. * @returns the current updated Vector3
  3044. */
  3045. Vector3.prototype.set = function (x, y, z) {
  3046. return this.copyFromFloats(x, y, z);
  3047. };
  3048. // Statics
  3049. /**
  3050. * Get the clip factor between two vectors
  3051. * @param vector0 defines the first operand
  3052. * @param vector1 defines the second operand
  3053. * @param axis defines the axis to use
  3054. * @param size defines the size along the axis
  3055. * @returns the clip factor
  3056. */
  3057. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3058. var d0 = Vector3.Dot(vector0, axis) - size;
  3059. var d1 = Vector3.Dot(vector1, axis) - size;
  3060. var s = d0 / (d0 - d1);
  3061. return s;
  3062. };
  3063. /**
  3064. * Get angle between two vectors
  3065. * @param vector0 angle between vector0 and vector1
  3066. * @param vector1 angle between vector0 and vector1
  3067. * @param normal direction of the normal
  3068. * @return the angle between vector0 and vector1
  3069. */
  3070. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3071. var v0 = vector0.clone().normalize();
  3072. var v1 = vector1.clone().normalize();
  3073. var dot = Vector3.Dot(v0, v1);
  3074. var n = Vector3.Cross(v0, v1);
  3075. if (Vector3.Dot(n, normal) > 0) {
  3076. return Math.acos(dot);
  3077. }
  3078. return -Math.acos(dot);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set from the index "offset" of the passed array
  3082. * @param array defines the source array
  3083. * @param offset defines the offset in the source array
  3084. * @returns the new Vector3
  3085. */
  3086. Vector3.FromArray = function (array, offset) {
  3087. if (!offset) {
  3088. offset = 0;
  3089. }
  3090. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3091. };
  3092. /**
  3093. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3094. * This function is deprecated. Use FromArray instead
  3095. * @param array defines the source array
  3096. * @param offset defines the offset in the source array
  3097. * @returns the new Vector3
  3098. */
  3099. Vector3.FromFloatArray = function (array, offset) {
  3100. return Vector3.FromArray(array, offset);
  3101. };
  3102. /**
  3103. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3104. * @param array defines the source array
  3105. * @param offset defines the offset in the source array
  3106. * @param result defines the Vector3 where to store the result
  3107. */
  3108. Vector3.FromArrayToRef = function (array, offset, result) {
  3109. result.x = array[offset];
  3110. result.y = array[offset + 1];
  3111. result.z = array[offset + 2];
  3112. };
  3113. /**
  3114. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3115. * This function is deprecated. Use FromArrayToRef instead.
  3116. * @param array defines the source array
  3117. * @param offset defines the offset in the source array
  3118. * @param result defines the Vector3 where to store the result
  3119. */
  3120. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3121. return Vector3.FromArrayToRef(array, offset, result);
  3122. };
  3123. /**
  3124. * Sets the passed vector "result" with the passed floats.
  3125. * @param x defines the x coordinate of the source
  3126. * @param y defines the y coordinate of the source
  3127. * @param z defines the z coordinate of the source
  3128. * @param result defines the Vector3 where to store the result
  3129. */
  3130. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3131. result.x = x;
  3132. result.y = y;
  3133. result.z = z;
  3134. };
  3135. /**
  3136. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3137. * @returns a new empty Vector3
  3138. */
  3139. Vector3.Zero = function () {
  3140. return new Vector3(0.0, 0.0, 0.0);
  3141. };
  3142. /**
  3143. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3144. * @returns a new unit Vector3
  3145. */
  3146. Vector3.One = function () {
  3147. return new Vector3(1.0, 1.0, 1.0);
  3148. };
  3149. /**
  3150. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3151. * @returns a new up Vector3
  3152. */
  3153. Vector3.Up = function () {
  3154. return new Vector3(0.0, 1.0, 0.0);
  3155. };
  3156. /**
  3157. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3158. * @returns a new forward Vector3
  3159. */
  3160. Vector3.Forward = function () {
  3161. return new Vector3(0.0, 0.0, 1.0);
  3162. };
  3163. /**
  3164. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3165. * @returns a new right Vector3
  3166. */
  3167. Vector3.Right = function () {
  3168. return new Vector3(1.0, 0.0, 0.0);
  3169. };
  3170. /**
  3171. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3172. * @returns a new left Vector3
  3173. */
  3174. Vector3.Left = function () {
  3175. return new Vector3(-1.0, 0.0, 0.0);
  3176. };
  3177. /**
  3178. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3179. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3180. * @param vector defines the Vector3 to transform
  3181. * @param transformation defines the transformation matrix
  3182. * @returns the transformed Vector3
  3183. */
  3184. Vector3.TransformCoordinates = function (vector, transformation) {
  3185. var result = Vector3.Zero();
  3186. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3187. return result;
  3188. };
  3189. /**
  3190. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3191. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3192. * @param vector defines the Vector3 to transform
  3193. * @param transformation defines the transformation matrix
  3194. * @param result defines the Vector3 where to store the result
  3195. */
  3196. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3197. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3198. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3199. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3200. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3201. result.x = x / w;
  3202. result.y = y / w;
  3203. result.z = z / w;
  3204. };
  3205. /**
  3206. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3207. * This method computes tranformed coordinates only, not transformed direction vectors
  3208. * @param x define the x coordinate of the source vector
  3209. * @param y define the y coordinate of the source vector
  3210. * @param z define the z coordinate of the source vector
  3211. * @param transformation defines the transformation matrix
  3212. * @param result defines the Vector3 where to store the result
  3213. */
  3214. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3215. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3216. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3217. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3218. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3219. result.x = rx / rw;
  3220. result.y = ry / rw;
  3221. result.z = rz / rw;
  3222. };
  3223. /**
  3224. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3225. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3226. * @param vector defines the Vector3 to transform
  3227. * @param transformation defines the transformation matrix
  3228. * @returns the new Vector3
  3229. */
  3230. Vector3.TransformNormal = function (vector, transformation) {
  3231. var result = Vector3.Zero();
  3232. Vector3.TransformNormalToRef(vector, transformation, result);
  3233. return result;
  3234. };
  3235. /**
  3236. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3237. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3238. * @param vector defines the Vector3 to transform
  3239. * @param transformation defines the transformation matrix
  3240. * @param result defines the Vector3 where to store the result
  3241. */
  3242. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3243. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3244. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3245. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3246. result.x = x;
  3247. result.y = y;
  3248. result.z = z;
  3249. };
  3250. /**
  3251. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3252. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3253. * @param x define the x coordinate of the source vector
  3254. * @param y define the y coordinate of the source vector
  3255. * @param z define the z coordinate of the source vector
  3256. * @param transformation defines the transformation matrix
  3257. * @param result defines the Vector3 where to store the result
  3258. */
  3259. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3260. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3261. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3262. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3263. };
  3264. /**
  3265. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3266. * @param value1 defines the first control point
  3267. * @param value2 defines the second control point
  3268. * @param value3 defines the third control point
  3269. * @param value4 defines the fourth control point
  3270. * @param amount defines the amount on the spline to use
  3271. * @returns the new Vector3
  3272. */
  3273. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3274. var squared = amount * amount;
  3275. var cubed = amount * squared;
  3276. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3277. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3278. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3279. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3280. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3281. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3282. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3283. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3284. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3285. return new Vector3(x, y, z);
  3286. };
  3287. /**
  3288. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3289. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3290. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3291. * @param value defines the current value
  3292. * @param min defines the lower range value
  3293. * @param max defines the upper range value
  3294. * @returns the new Vector3
  3295. */
  3296. Vector3.Clamp = function (value, min, max) {
  3297. var x = value.x;
  3298. x = (x > max.x) ? max.x : x;
  3299. x = (x < min.x) ? min.x : x;
  3300. var y = value.y;
  3301. y = (y > max.y) ? max.y : y;
  3302. y = (y < min.y) ? min.y : y;
  3303. var z = value.z;
  3304. z = (z > max.z) ? max.z : z;
  3305. z = (z < min.z) ? min.z : z;
  3306. return new Vector3(x, y, z);
  3307. };
  3308. /**
  3309. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3310. * @param value1 defines the first control point
  3311. * @param tangent1 defines the first tangent vector
  3312. * @param value2 defines the second control point
  3313. * @param tangent2 defines the second tangent vector
  3314. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3315. * @returns the new Vector3
  3316. */
  3317. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3318. var squared = amount * amount;
  3319. var cubed = amount * squared;
  3320. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3321. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3322. var part3 = (cubed - (2.0 * squared)) + amount;
  3323. var part4 = cubed - squared;
  3324. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3325. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3326. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3327. return new Vector3(x, y, z);
  3328. };
  3329. /**
  3330. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3331. * @param start defines the start value
  3332. * @param end defines the end value
  3333. * @param amount max defines amount between both (between 0 and 1)
  3334. * @returns the new Vector3
  3335. */
  3336. Vector3.Lerp = function (start, end, amount) {
  3337. var result = new Vector3(0, 0, 0);
  3338. Vector3.LerpToRef(start, end, amount, result);
  3339. return result;
  3340. };
  3341. /**
  3342. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3343. * @param start defines the start value
  3344. * @param end defines the end value
  3345. * @param amount max defines amount between both (between 0 and 1)
  3346. * @param result defines the Vector3 where to store the result
  3347. */
  3348. Vector3.LerpToRef = function (start, end, amount, result) {
  3349. result.x = start.x + ((end.x - start.x) * amount);
  3350. result.y = start.y + ((end.y - start.y) * amount);
  3351. result.z = start.z + ((end.z - start.z) * amount);
  3352. };
  3353. /**
  3354. * Returns the dot product (float) between the vectors "left" and "right"
  3355. * @param left defines the left operand
  3356. * @param right defines the right operand
  3357. * @returns the dot product
  3358. */
  3359. Vector3.Dot = function (left, right) {
  3360. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3361. };
  3362. /**
  3363. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3364. * The cross product is then orthogonal to both "left" and "right"
  3365. * @param left defines the left operand
  3366. * @param right defines the right operand
  3367. * @returns the cross product
  3368. */
  3369. Vector3.Cross = function (left, right) {
  3370. var result = Vector3.Zero();
  3371. Vector3.CrossToRef(left, right, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Sets the passed vector "result" with the cross product of "left" and "right"
  3376. * The cross product is then orthogonal to both "left" and "right"
  3377. * @param left defines the left operand
  3378. * @param right defines the right operand
  3379. * @param result defines the Vector3 where to store the result
  3380. */
  3381. Vector3.CrossToRef = function (left, right, result) {
  3382. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3383. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3384. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3385. result.copyFrom(MathTmp.Vector3[0]);
  3386. };
  3387. /**
  3388. * Returns a new Vector3 as the normalization of the passed vector
  3389. * @param vector defines the Vector3 to normalize
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.Normalize = function (vector) {
  3393. var result = Vector3.Zero();
  3394. Vector3.NormalizeToRef(vector, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the passed vector "result" with the normalization of the passed first vector
  3399. * @param vector defines the Vector3 to normalize
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.NormalizeToRef = function (vector, result) {
  3403. result.copyFrom(vector);
  3404. result.normalize();
  3405. };
  3406. /**
  3407. * Project a Vector3 onto screen space
  3408. * @param vector defines the Vector3 to project
  3409. * @param world defines the world matrix to use
  3410. * @param transform defines the transform (view x projection) matrix to use
  3411. * @param viewport defines the screen viewport to use
  3412. * @returns the new Vector3
  3413. */
  3414. Vector3.Project = function (vector, world, transform, viewport) {
  3415. var cw = viewport.width;
  3416. var ch = viewport.height;
  3417. var cx = viewport.x;
  3418. var cy = viewport.y;
  3419. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3420. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3421. var matrix = MathTmp.Matrix[0];
  3422. world.multiplyToRef(transform, matrix);
  3423. matrix.multiplyToRef(viewportMatrix, matrix);
  3424. return Vector3.TransformCoordinates(vector, matrix);
  3425. };
  3426. /**
  3427. * Unproject from screen space to object space
  3428. * @param source defines the screen space Vector3 to use
  3429. * @param viewportWidth defines the current width of the viewport
  3430. * @param viewportHeight defines the current height of the viewport
  3431. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3432. * @param transform defines the transform (view x projection) matrix to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3436. var matrix = MathTmp.Matrix[0];
  3437. world.multiplyToRef(transform, matrix);
  3438. matrix.invert();
  3439. source.x = source.x / viewportWidth * 2 - 1;
  3440. source.y = -(source.y / viewportHeight * 2 - 1);
  3441. var vector = Vector3.TransformCoordinates(source, matrix);
  3442. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3443. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3444. vector = vector.scale(1.0 / num);
  3445. }
  3446. return vector;
  3447. };
  3448. /**
  3449. * Unproject from screen space to object space
  3450. * @param source defines the screen space Vector3 to use
  3451. * @param viewportWidth defines the current width of the viewport
  3452. * @param viewportHeight defines the current height of the viewport
  3453. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3454. * @param view defines the view matrix to use
  3455. * @param projection defines the projection matrix to use
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3459. var result = Vector3.Zero();
  3460. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3461. return result;
  3462. };
  3463. /**
  3464. * Unproject from screen space to object space
  3465. * @param source defines the screen space Vector3 to use
  3466. * @param viewportWidth defines the current width of the viewport
  3467. * @param viewportHeight defines the current height of the viewport
  3468. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3469. * @param view defines the view matrix to use
  3470. * @param projection defines the projection matrix to use
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3474. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3475. };
  3476. /**
  3477. * Unproject from screen space to object space
  3478. * @param sourceX defines the screen space x coordinate to use
  3479. * @param sourceY defines the screen space y coordinate to use
  3480. * @param sourceZ defines the screen space z coordinate to use
  3481. * @param viewportWidth defines the current width of the viewport
  3482. * @param viewportHeight defines the current height of the viewport
  3483. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3484. * @param view defines the view matrix to use
  3485. * @param projection defines the projection matrix to use
  3486. * @param result defines the Vector3 where to store the result
  3487. */
  3488. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3489. var matrix = MathTmp.Matrix[0];
  3490. world.multiplyToRef(view, matrix);
  3491. matrix.multiplyToRef(projection, matrix);
  3492. matrix.invert();
  3493. var screenSource = MathTmp.Vector3[0];
  3494. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3495. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3496. screenSource.z = 2 * sourceZ - 1.0;
  3497. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3498. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3499. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3500. result.scaleInPlace(1.0 / num);
  3501. }
  3502. };
  3503. /**
  3504. * Gets the minimal coordinate values between two Vector3
  3505. * @param left defines the first operand
  3506. * @param right defines the second operand
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Minimize = function (left, right) {
  3510. var min = left.clone();
  3511. min.minimizeInPlace(right);
  3512. return min;
  3513. };
  3514. /**
  3515. * Gets the maximal coordinate values between two Vector3
  3516. * @param left defines the first operand
  3517. * @param right defines the second operand
  3518. * @returns the new Vector3
  3519. */
  3520. Vector3.Maximize = function (left, right) {
  3521. var max = left.clone();
  3522. max.maximizeInPlace(right);
  3523. return max;
  3524. };
  3525. /**
  3526. * Returns the distance between the vectors "value1" and "value2"
  3527. * @param value1 defines the first operand
  3528. * @param value2 defines the second operand
  3529. * @returns the distance
  3530. */
  3531. Vector3.Distance = function (value1, value2) {
  3532. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3533. };
  3534. /**
  3535. * Returns the squared distance between the vectors "value1" and "value2"
  3536. * @param value1 defines the first operand
  3537. * @param value2 defines the second operand
  3538. * @returns the squared distance
  3539. */
  3540. Vector3.DistanceSquared = function (value1, value2) {
  3541. var x = value1.x - value2.x;
  3542. var y = value1.y - value2.y;
  3543. var z = value1.z - value2.z;
  3544. return (x * x) + (y * y) + (z * z);
  3545. };
  3546. /**
  3547. * Returns a new Vector3 located at the center between "value1" and "value2"
  3548. * @param value1 defines the first operand
  3549. * @param value2 defines the second operand
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Center = function (value1, value2) {
  3553. var center = value1.add(value2);
  3554. center.scaleInPlace(0.5);
  3555. return center;
  3556. };
  3557. /**
  3558. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3559. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3560. * to something in order to rotate it from its local system to the given target system
  3561. * Note: axis1, axis2 and axis3 are normalized during this operation
  3562. * @param axis1 defines the first axis
  3563. * @param axis2 defines the second axis
  3564. * @param axis3 defines the third axis
  3565. * @returns a new Vector3
  3566. */
  3567. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3568. var rotation = Vector3.Zero();
  3569. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3570. return rotation;
  3571. };
  3572. /**
  3573. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3574. * @param axis1 defines the first axis
  3575. * @param axis2 defines the second axis
  3576. * @param axis3 defines the third axis
  3577. * @param ref defines the Vector3 where to store the result
  3578. */
  3579. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3580. var quat = MathTmp.Quaternion[0];
  3581. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3582. quat.toEulerAnglesToRef(ref);
  3583. };
  3584. return Vector3;
  3585. }());
  3586. BABYLON.Vector3 = Vector3;
  3587. //Vector4 class created for EulerAngle class conversion to Quaternion
  3588. var Vector4 = /** @class */ (function () {
  3589. /**
  3590. * Creates a Vector4 object from the passed floats.
  3591. */
  3592. function Vector4(x, y, z, w) {
  3593. this.x = x;
  3594. this.y = y;
  3595. this.z = z;
  3596. this.w = w;
  3597. }
  3598. /**
  3599. * Returns the string with the Vector4 coordinates.
  3600. */
  3601. Vector4.prototype.toString = function () {
  3602. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3603. };
  3604. /**
  3605. * Returns the string "Vector4".
  3606. */
  3607. Vector4.prototype.getClassName = function () {
  3608. return "Vector4";
  3609. };
  3610. /**
  3611. * Returns the Vector4 hash code.
  3612. */
  3613. Vector4.prototype.getHashCode = function () {
  3614. var hash = this.x || 0;
  3615. hash = (hash * 397) ^ (this.y || 0);
  3616. hash = (hash * 397) ^ (this.z || 0);
  3617. hash = (hash * 397) ^ (this.w || 0);
  3618. return hash;
  3619. };
  3620. // Operators
  3621. /**
  3622. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3623. */
  3624. Vector4.prototype.asArray = function () {
  3625. var result = new Array();
  3626. this.toArray(result, 0);
  3627. return result;
  3628. };
  3629. /**
  3630. * Populates the passed array from the passed index with the Vector4 coordinates.
  3631. * Returns the Vector4.
  3632. */
  3633. Vector4.prototype.toArray = function (array, index) {
  3634. if (index === undefined) {
  3635. index = 0;
  3636. }
  3637. array[index] = this.x;
  3638. array[index + 1] = this.y;
  3639. array[index + 2] = this.z;
  3640. array[index + 3] = this.w;
  3641. return this;
  3642. };
  3643. /**
  3644. * Adds the passed vector to the current Vector4.
  3645. * Returns the updated Vector4.
  3646. */
  3647. Vector4.prototype.addInPlace = function (otherVector) {
  3648. this.x += otherVector.x;
  3649. this.y += otherVector.y;
  3650. this.z += otherVector.z;
  3651. this.w += otherVector.w;
  3652. return this;
  3653. };
  3654. /**
  3655. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3656. */
  3657. Vector4.prototype.add = function (otherVector) {
  3658. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3659. };
  3660. /**
  3661. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3662. * Returns the current Vector4.
  3663. */
  3664. Vector4.prototype.addToRef = function (otherVector, result) {
  3665. result.x = this.x + otherVector.x;
  3666. result.y = this.y + otherVector.y;
  3667. result.z = this.z + otherVector.z;
  3668. result.w = this.w + otherVector.w;
  3669. return this;
  3670. };
  3671. /**
  3672. * Subtract in place the passed vector from the current Vector4.
  3673. * Returns the updated Vector4.
  3674. */
  3675. Vector4.prototype.subtractInPlace = function (otherVector) {
  3676. this.x -= otherVector.x;
  3677. this.y -= otherVector.y;
  3678. this.z -= otherVector.z;
  3679. this.w -= otherVector.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3684. */
  3685. Vector4.prototype.subtract = function (otherVector) {
  3686. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3687. };
  3688. /**
  3689. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3690. * Returns the current Vector4.
  3691. */
  3692. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3693. result.x = this.x - otherVector.x;
  3694. result.y = this.y - otherVector.y;
  3695. result.z = this.z - otherVector.z;
  3696. result.w = this.w - otherVector.w;
  3697. return this;
  3698. };
  3699. /**
  3700. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3701. */
  3702. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3703. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3704. };
  3705. /**
  3706. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3707. * Returns the current Vector4.
  3708. */
  3709. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3710. result.x = this.x - x;
  3711. result.y = this.y - y;
  3712. result.z = this.z - z;
  3713. result.w = this.w - w;
  3714. return this;
  3715. };
  3716. /**
  3717. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3718. */
  3719. Vector4.prototype.negate = function () {
  3720. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3721. };
  3722. /**
  3723. * Multiplies the current Vector4 coordinates by scale (float).
  3724. * Returns the updated Vector4.
  3725. */
  3726. Vector4.prototype.scaleInPlace = function (scale) {
  3727. this.x *= scale;
  3728. this.y *= scale;
  3729. this.z *= scale;
  3730. this.w *= scale;
  3731. return this;
  3732. };
  3733. /**
  3734. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3735. */
  3736. Vector4.prototype.scale = function (scale) {
  3737. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3738. };
  3739. /**
  3740. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3741. * Returns the current Vector4.
  3742. */
  3743. Vector4.prototype.scaleToRef = function (scale, result) {
  3744. result.x = this.x * scale;
  3745. result.y = this.y * scale;
  3746. result.z = this.z * scale;
  3747. result.w = this.w * scale;
  3748. return this;
  3749. };
  3750. /**
  3751. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3752. */
  3753. Vector4.prototype.equals = function (otherVector) {
  3754. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3755. };
  3756. /**
  3757. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3758. */
  3759. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3760. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3761. return otherVector
  3762. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3763. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3764. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3765. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3766. };
  3767. /**
  3768. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3769. */
  3770. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3771. return this.x === x && this.y === y && this.z === z && this.w === w;
  3772. };
  3773. /**
  3774. * Multiplies in place the current Vector4 by the passed one.
  3775. * Returns the updated Vector4.
  3776. */
  3777. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3778. this.x *= otherVector.x;
  3779. this.y *= otherVector.y;
  3780. this.z *= otherVector.z;
  3781. this.w *= otherVector.w;
  3782. return this;
  3783. };
  3784. /**
  3785. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3786. */
  3787. Vector4.prototype.multiply = function (otherVector) {
  3788. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3789. };
  3790. /**
  3791. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3792. * Returns the current Vector4.
  3793. */
  3794. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3795. result.x = this.x * otherVector.x;
  3796. result.y = this.y * otherVector.y;
  3797. result.z = this.z * otherVector.z;
  3798. result.w = this.w * otherVector.w;
  3799. return this;
  3800. };
  3801. /**
  3802. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3803. */
  3804. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3805. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3806. };
  3807. /**
  3808. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3809. */
  3810. Vector4.prototype.divide = function (otherVector) {
  3811. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3812. };
  3813. /**
  3814. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3815. * Returns the current Vector4.
  3816. */
  3817. Vector4.prototype.divideToRef = function (otherVector, result) {
  3818. result.x = this.x / otherVector.x;
  3819. result.y = this.y / otherVector.y;
  3820. result.z = this.z / otherVector.z;
  3821. result.w = this.w / otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Divides the current Vector3 coordinates by the passed ones.
  3826. * @returns the updated Vector3.
  3827. */
  3828. Vector4.prototype.divideInPlace = function (otherVector) {
  3829. return this.divideToRef(otherVector, this);
  3830. };
  3831. /**
  3832. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3833. * @param other defines the second operand
  3834. * @returns the current updated Vector4
  3835. */
  3836. Vector4.prototype.minimizeInPlace = function (other) {
  3837. if (other.x < this.x)
  3838. this.x = other.x;
  3839. if (other.y < this.y)
  3840. this.y = other.y;
  3841. if (other.z < this.z)
  3842. this.z = other.z;
  3843. if (other.w < this.w)
  3844. this.w = other.w;
  3845. return this;
  3846. };
  3847. /**
  3848. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3849. * @param other defines the second operand
  3850. * @returns the current updated Vector4
  3851. */
  3852. Vector4.prototype.maximizeInPlace = function (other) {
  3853. if (other.x > this.x)
  3854. this.x = other.x;
  3855. if (other.y > this.y)
  3856. this.y = other.y;
  3857. if (other.z > this.z)
  3858. this.z = other.z;
  3859. if (other.w > this.w)
  3860. this.w = other.w;
  3861. return this;
  3862. };
  3863. // Properties
  3864. /**
  3865. * Returns the Vector4 length (float).
  3866. */
  3867. Vector4.prototype.length = function () {
  3868. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3869. };
  3870. /**
  3871. * Returns the Vector4 squared length (float).
  3872. */
  3873. Vector4.prototype.lengthSquared = function () {
  3874. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3875. };
  3876. // Methods
  3877. /**
  3878. * Normalizes in place the Vector4.
  3879. * Returns the updated Vector4.
  3880. */
  3881. Vector4.prototype.normalize = function () {
  3882. var len = this.length();
  3883. if (len === 0)
  3884. return this;
  3885. var num = 1.0 / len;
  3886. this.x *= num;
  3887. this.y *= num;
  3888. this.z *= num;
  3889. this.w *= num;
  3890. return this;
  3891. };
  3892. /**
  3893. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3894. */
  3895. Vector4.prototype.toVector3 = function () {
  3896. return new Vector3(this.x, this.y, this.z);
  3897. };
  3898. /**
  3899. * Returns a new Vector4 copied from the current one.
  3900. */
  3901. Vector4.prototype.clone = function () {
  3902. return new Vector4(this.x, this.y, this.z, this.w);
  3903. };
  3904. /**
  3905. * Updates the current Vector4 with the passed one coordinates.
  3906. * Returns the updated Vector4.
  3907. */
  3908. Vector4.prototype.copyFrom = function (source) {
  3909. this.x = source.x;
  3910. this.y = source.y;
  3911. this.z = source.z;
  3912. this.w = source.w;
  3913. return this;
  3914. };
  3915. /**
  3916. * Updates the current Vector4 coordinates with the passed floats.
  3917. * Returns the updated Vector4.
  3918. */
  3919. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3920. this.x = x;
  3921. this.y = y;
  3922. this.z = z;
  3923. this.w = w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Updates the current Vector4 coordinates with the passed floats.
  3928. * Returns the updated Vector4.
  3929. */
  3930. Vector4.prototype.set = function (x, y, z, w) {
  3931. return this.copyFromFloats(x, y, z, w);
  3932. };
  3933. // Statics
  3934. /**
  3935. * Returns a new Vector4 set from the starting index of the passed array.
  3936. */
  3937. Vector4.FromArray = function (array, offset) {
  3938. if (!offset) {
  3939. offset = 0;
  3940. }
  3941. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3942. };
  3943. /**
  3944. * Updates the passed vector "result" from the starting index of the passed array.
  3945. */
  3946. Vector4.FromArrayToRef = function (array, offset, result) {
  3947. result.x = array[offset];
  3948. result.y = array[offset + 1];
  3949. result.z = array[offset + 2];
  3950. result.w = array[offset + 3];
  3951. };
  3952. /**
  3953. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3954. */
  3955. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3956. Vector4.FromArrayToRef(array, offset, result);
  3957. };
  3958. /**
  3959. * Updates the passed vector "result" coordinates from the passed floats.
  3960. */
  3961. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3962. result.x = x;
  3963. result.y = y;
  3964. result.z = z;
  3965. result.w = w;
  3966. };
  3967. /**
  3968. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3969. */
  3970. Vector4.Zero = function () {
  3971. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3972. };
  3973. /**
  3974. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3975. */
  3976. Vector4.One = function () {
  3977. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3978. };
  3979. /**
  3980. * Returns a new normalized Vector4 from the passed one.
  3981. */
  3982. Vector4.Normalize = function (vector) {
  3983. var result = Vector4.Zero();
  3984. Vector4.NormalizeToRef(vector, result);
  3985. return result;
  3986. };
  3987. /**
  3988. * Updates the passed vector "result" from the normalization of the passed one.
  3989. */
  3990. Vector4.NormalizeToRef = function (vector, result) {
  3991. result.copyFrom(vector);
  3992. result.normalize();
  3993. };
  3994. Vector4.Minimize = function (left, right) {
  3995. var min = left.clone();
  3996. min.minimizeInPlace(right);
  3997. return min;
  3998. };
  3999. Vector4.Maximize = function (left, right) {
  4000. var max = left.clone();
  4001. max.maximizeInPlace(right);
  4002. return max;
  4003. };
  4004. /**
  4005. * Returns the distance (float) between the vectors "value1" and "value2".
  4006. */
  4007. Vector4.Distance = function (value1, value2) {
  4008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4009. };
  4010. /**
  4011. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4012. */
  4013. Vector4.DistanceSquared = function (value1, value2) {
  4014. var x = value1.x - value2.x;
  4015. var y = value1.y - value2.y;
  4016. var z = value1.z - value2.z;
  4017. var w = value1.w - value2.w;
  4018. return (x * x) + (y * y) + (z * z) + (w * w);
  4019. };
  4020. /**
  4021. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4022. */
  4023. Vector4.Center = function (value1, value2) {
  4024. var center = value1.add(value2);
  4025. center.scaleInPlace(0.5);
  4026. return center;
  4027. };
  4028. /**
  4029. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4030. * This methods computes transformed normalized direction vectors only.
  4031. */
  4032. Vector4.TransformNormal = function (vector, transformation) {
  4033. var result = Vector4.Zero();
  4034. Vector4.TransformNormalToRef(vector, transformation, result);
  4035. return result;
  4036. };
  4037. /**
  4038. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4039. * This methods computes transformed normalized direction vectors only.
  4040. */
  4041. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4042. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4043. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4044. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4045. result.x = x;
  4046. result.y = y;
  4047. result.z = z;
  4048. result.w = vector.w;
  4049. };
  4050. /**
  4051. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4052. * This methods computes transformed normalized direction vectors only.
  4053. */
  4054. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4055. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4056. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4057. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4058. result.w = w;
  4059. };
  4060. return Vector4;
  4061. }());
  4062. BABYLON.Vector4 = Vector4;
  4063. var Size = /** @class */ (function () {
  4064. /**
  4065. * Creates a Size object from the passed width and height (floats).
  4066. */
  4067. function Size(width, height) {
  4068. this.width = width;
  4069. this.height = height;
  4070. }
  4071. // Returns a string with the Size width and height.
  4072. Size.prototype.toString = function () {
  4073. return "{W: " + this.width + ", H: " + this.height + "}";
  4074. };
  4075. /**
  4076. * Returns the string "Size"
  4077. */
  4078. Size.prototype.getClassName = function () {
  4079. return "Size";
  4080. };
  4081. /**
  4082. * Returns the Size hash code.
  4083. */
  4084. Size.prototype.getHashCode = function () {
  4085. var hash = this.width || 0;
  4086. hash = (hash * 397) ^ (this.height || 0);
  4087. return hash;
  4088. };
  4089. /**
  4090. * Updates the current size from the passed one.
  4091. * Returns the updated Size.
  4092. */
  4093. Size.prototype.copyFrom = function (src) {
  4094. this.width = src.width;
  4095. this.height = src.height;
  4096. };
  4097. /**
  4098. * Updates in place the current Size from the passed floats.
  4099. * Returns the updated Size.
  4100. */
  4101. Size.prototype.copyFromFloats = function (width, height) {
  4102. this.width = width;
  4103. this.height = height;
  4104. return this;
  4105. };
  4106. /**
  4107. * Updates in place the current Size from the passed floats.
  4108. * Returns the updated Size.
  4109. */
  4110. Size.prototype.set = function (width, height) {
  4111. return this.copyFromFloats(width, height);
  4112. };
  4113. /**
  4114. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4115. */
  4116. Size.prototype.multiplyByFloats = function (w, h) {
  4117. return new Size(this.width * w, this.height * h);
  4118. };
  4119. /**
  4120. * Returns a new Size copied from the passed one.
  4121. */
  4122. Size.prototype.clone = function () {
  4123. return new Size(this.width, this.height);
  4124. };
  4125. /**
  4126. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4127. */
  4128. Size.prototype.equals = function (other) {
  4129. if (!other) {
  4130. return false;
  4131. }
  4132. return (this.width === other.width) && (this.height === other.height);
  4133. };
  4134. Object.defineProperty(Size.prototype, "surface", {
  4135. /**
  4136. * Returns the surface of the Size : width * height (float).
  4137. */
  4138. get: function () {
  4139. return this.width * this.height;
  4140. },
  4141. enumerable: true,
  4142. configurable: true
  4143. });
  4144. /**
  4145. * Returns a new Size set to (0.0, 0.0)
  4146. */
  4147. Size.Zero = function () {
  4148. return new Size(0.0, 0.0);
  4149. };
  4150. /**
  4151. * Returns a new Size set as the addition result of the current Size and the passed one.
  4152. */
  4153. Size.prototype.add = function (otherSize) {
  4154. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4155. return r;
  4156. };
  4157. /**
  4158. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4159. */
  4160. Size.prototype.subtract = function (otherSize) {
  4161. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4162. return r;
  4163. };
  4164. /**
  4165. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4166. */
  4167. Size.Lerp = function (start, end, amount) {
  4168. var w = start.width + ((end.width - start.width) * amount);
  4169. var h = start.height + ((end.height - start.height) * amount);
  4170. return new Size(w, h);
  4171. };
  4172. return Size;
  4173. }());
  4174. BABYLON.Size = Size;
  4175. var Quaternion = /** @class */ (function () {
  4176. /**
  4177. * Creates a new Quaternion from the passed floats.
  4178. */
  4179. function Quaternion(x, y, z, w) {
  4180. if (x === void 0) { x = 0.0; }
  4181. if (y === void 0) { y = 0.0; }
  4182. if (z === void 0) { z = 0.0; }
  4183. if (w === void 0) { w = 1.0; }
  4184. this.x = x;
  4185. this.y = y;
  4186. this.z = z;
  4187. this.w = w;
  4188. }
  4189. /**
  4190. * Returns a string with the Quaternion coordinates.
  4191. */
  4192. Quaternion.prototype.toString = function () {
  4193. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4194. };
  4195. /**
  4196. * Returns the string "Quaternion".
  4197. */
  4198. Quaternion.prototype.getClassName = function () {
  4199. return "Quaternion";
  4200. };
  4201. /**
  4202. * Returns the Quaternion hash code.
  4203. */
  4204. Quaternion.prototype.getHashCode = function () {
  4205. var hash = this.x || 0;
  4206. hash = (hash * 397) ^ (this.y || 0);
  4207. hash = (hash * 397) ^ (this.z || 0);
  4208. hash = (hash * 397) ^ (this.w || 0);
  4209. return hash;
  4210. };
  4211. /**
  4212. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4213. */
  4214. Quaternion.prototype.asArray = function () {
  4215. return [this.x, this.y, this.z, this.w];
  4216. };
  4217. /**
  4218. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4219. */
  4220. Quaternion.prototype.equals = function (otherQuaternion) {
  4221. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4222. };
  4223. /**
  4224. * Returns a new Quaternion copied from the current one.
  4225. */
  4226. Quaternion.prototype.clone = function () {
  4227. return new Quaternion(this.x, this.y, this.z, this.w);
  4228. };
  4229. /**
  4230. * Updates the current Quaternion from the passed one coordinates.
  4231. * Returns the updated Quaterion.
  4232. */
  4233. Quaternion.prototype.copyFrom = function (other) {
  4234. this.x = other.x;
  4235. this.y = other.y;
  4236. this.z = other.z;
  4237. this.w = other.w;
  4238. return this;
  4239. };
  4240. /**
  4241. * Updates the current Quaternion from the passed float coordinates.
  4242. * Returns the updated Quaterion.
  4243. */
  4244. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4245. this.x = x;
  4246. this.y = y;
  4247. this.z = z;
  4248. this.w = w;
  4249. return this;
  4250. };
  4251. /**
  4252. * Updates the current Quaternion from the passed float coordinates.
  4253. * Returns the updated Quaterion.
  4254. */
  4255. Quaternion.prototype.set = function (x, y, z, w) {
  4256. return this.copyFromFloats(x, y, z, w);
  4257. };
  4258. /**
  4259. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4260. */
  4261. Quaternion.prototype.add = function (other) {
  4262. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4263. };
  4264. /**
  4265. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4266. */
  4267. Quaternion.prototype.subtract = function (other) {
  4268. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4269. };
  4270. /**
  4271. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4272. */
  4273. Quaternion.prototype.scale = function (value) {
  4274. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4275. };
  4276. /**
  4277. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4278. */
  4279. Quaternion.prototype.multiply = function (q1) {
  4280. var result = new Quaternion(0, 0, 0, 1.0);
  4281. this.multiplyToRef(q1, result);
  4282. return result;
  4283. };
  4284. /**
  4285. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4286. * Returns the current Quaternion.
  4287. */
  4288. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4289. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4290. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4291. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4292. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4293. result.copyFromFloats(x, y, z, w);
  4294. return this;
  4295. };
  4296. /**
  4297. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4298. * Returns the updated Quaternion.
  4299. */
  4300. Quaternion.prototype.multiplyInPlace = function (q1) {
  4301. this.multiplyToRef(q1, this);
  4302. return this;
  4303. };
  4304. /**
  4305. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4306. * Returns the current Quaternion.
  4307. */
  4308. Quaternion.prototype.conjugateToRef = function (ref) {
  4309. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4310. return this;
  4311. };
  4312. /**
  4313. * Conjugates in place the current Quaternion.
  4314. * Returns the updated Quaternion.
  4315. */
  4316. Quaternion.prototype.conjugateInPlace = function () {
  4317. this.x *= -1;
  4318. this.y *= -1;
  4319. this.z *= -1;
  4320. return this;
  4321. };
  4322. /**
  4323. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4324. */
  4325. Quaternion.prototype.conjugate = function () {
  4326. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4327. return result;
  4328. };
  4329. /**
  4330. * Returns the Quaternion length (float).
  4331. */
  4332. Quaternion.prototype.length = function () {
  4333. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4334. };
  4335. /**
  4336. * Normalize in place the current Quaternion.
  4337. * Returns the updated Quaternion.
  4338. */
  4339. Quaternion.prototype.normalize = function () {
  4340. var length = 1.0 / this.length();
  4341. this.x *= length;
  4342. this.y *= length;
  4343. this.z *= length;
  4344. this.w *= length;
  4345. return this;
  4346. };
  4347. /**
  4348. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4349. * @param order is a reserved parameter and is ignore for now
  4350. * @returns the new Vector3
  4351. */
  4352. Quaternion.prototype.toEulerAngles = function (order) {
  4353. if (order === void 0) { order = "YZX"; }
  4354. var result = Vector3.Zero();
  4355. this.toEulerAnglesToRef(result, order);
  4356. return result;
  4357. };
  4358. /**
  4359. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4360. * @param result defines the vector which will be filled with the Euler angles
  4361. * @param order is a reserved parameter and is ignore for now
  4362. * @returns the current Quaternion
  4363. */
  4364. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4365. if (order === void 0) { order = "YZX"; }
  4366. var qz = this.z;
  4367. var qx = this.x;
  4368. var qy = this.y;
  4369. var qw = this.w;
  4370. var sqw = qw * qw;
  4371. var sqz = qz * qz;
  4372. var sqx = qx * qx;
  4373. var sqy = qy * qy;
  4374. var zAxisY = qy * qz - qx * qw;
  4375. var limit = .4999999;
  4376. if (zAxisY < -limit) {
  4377. result.y = 2 * Math.atan2(qy, qw);
  4378. result.x = Math.PI / 2;
  4379. result.z = 0;
  4380. }
  4381. else if (zAxisY > limit) {
  4382. result.y = 2 * Math.atan2(qy, qw);
  4383. result.x = -Math.PI / 2;
  4384. result.z = 0;
  4385. }
  4386. else {
  4387. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4388. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4389. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4390. }
  4391. return this;
  4392. };
  4393. /**
  4394. * Updates the passed rotation matrix with the current Quaternion values.
  4395. * Returns the current Quaternion.
  4396. */
  4397. Quaternion.prototype.toRotationMatrix = function (result) {
  4398. var xx = this.x * this.x;
  4399. var yy = this.y * this.y;
  4400. var zz = this.z * this.z;
  4401. var xy = this.x * this.y;
  4402. var zw = this.z * this.w;
  4403. var zx = this.z * this.x;
  4404. var yw = this.y * this.w;
  4405. var yz = this.y * this.z;
  4406. var xw = this.x * this.w;
  4407. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4408. result.m[1] = 2.0 * (xy + zw);
  4409. result.m[2] = 2.0 * (zx - yw);
  4410. result.m[3] = 0;
  4411. result.m[4] = 2.0 * (xy - zw);
  4412. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4413. result.m[6] = 2.0 * (yz + xw);
  4414. result.m[7] = 0;
  4415. result.m[8] = 2.0 * (zx + yw);
  4416. result.m[9] = 2.0 * (yz - xw);
  4417. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4418. result.m[11] = 0;
  4419. result.m[12] = 0;
  4420. result.m[13] = 0;
  4421. result.m[14] = 0;
  4422. result.m[15] = 1.0;
  4423. result._markAsUpdated();
  4424. return this;
  4425. };
  4426. /**
  4427. * Updates the current Quaternion from the passed rotation matrix values.
  4428. * Returns the updated Quaternion.
  4429. */
  4430. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4431. Quaternion.FromRotationMatrixToRef(matrix, this);
  4432. return this;
  4433. };
  4434. // Statics
  4435. /**
  4436. * Returns a new Quaternion set from the passed rotation matrix values.
  4437. */
  4438. Quaternion.FromRotationMatrix = function (matrix) {
  4439. var result = new Quaternion();
  4440. Quaternion.FromRotationMatrixToRef(matrix, result);
  4441. return result;
  4442. };
  4443. /**
  4444. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4445. */
  4446. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4447. var data = matrix.m;
  4448. var m11 = data[0], m12 = data[4], m13 = data[8];
  4449. var m21 = data[1], m22 = data[5], m23 = data[9];
  4450. var m31 = data[2], m32 = data[6], m33 = data[10];
  4451. var trace = m11 + m22 + m33;
  4452. var s;
  4453. if (trace > 0) {
  4454. s = 0.5 / Math.sqrt(trace + 1.0);
  4455. result.w = 0.25 / s;
  4456. result.x = (m32 - m23) * s;
  4457. result.y = (m13 - m31) * s;
  4458. result.z = (m21 - m12) * s;
  4459. }
  4460. else if (m11 > m22 && m11 > m33) {
  4461. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4462. result.w = (m32 - m23) / s;
  4463. result.x = 0.25 * s;
  4464. result.y = (m12 + m21) / s;
  4465. result.z = (m13 + m31) / s;
  4466. }
  4467. else if (m22 > m33) {
  4468. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4469. result.w = (m13 - m31) / s;
  4470. result.x = (m12 + m21) / s;
  4471. result.y = 0.25 * s;
  4472. result.z = (m23 + m32) / s;
  4473. }
  4474. else {
  4475. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4476. result.w = (m21 - m12) / s;
  4477. result.x = (m13 + m31) / s;
  4478. result.y = (m23 + m32) / s;
  4479. result.z = 0.25 * s;
  4480. }
  4481. };
  4482. /**
  4483. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4484. */
  4485. Quaternion.Zero = function () {
  4486. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4487. };
  4488. /**
  4489. * Returns a new Quaternion as the inverted current Quaternion.
  4490. */
  4491. Quaternion.Inverse = function (q) {
  4492. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4493. };
  4494. /**
  4495. * Returns the identity Quaternion.
  4496. */
  4497. Quaternion.Identity = function () {
  4498. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4499. };
  4500. Quaternion.IsIdentity = function (quaternion) {
  4501. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4502. };
  4503. /**
  4504. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4505. */
  4506. Quaternion.RotationAxis = function (axis, angle) {
  4507. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4508. };
  4509. /**
  4510. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4511. */
  4512. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4513. var sin = Math.sin(angle / 2);
  4514. axis.normalize();
  4515. result.w = Math.cos(angle / 2);
  4516. result.x = axis.x * sin;
  4517. result.y = axis.y * sin;
  4518. result.z = axis.z * sin;
  4519. return result;
  4520. };
  4521. /**
  4522. * Retuns a new Quaternion set from the starting index of the passed array.
  4523. */
  4524. Quaternion.FromArray = function (array, offset) {
  4525. if (!offset) {
  4526. offset = 0;
  4527. }
  4528. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4529. };
  4530. /**
  4531. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4532. */
  4533. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4534. var q = new Quaternion();
  4535. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4536. return q;
  4537. };
  4538. /**
  4539. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4540. */
  4541. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4542. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4543. var halfRoll = roll * 0.5;
  4544. var halfPitch = pitch * 0.5;
  4545. var halfYaw = yaw * 0.5;
  4546. var sinRoll = Math.sin(halfRoll);
  4547. var cosRoll = Math.cos(halfRoll);
  4548. var sinPitch = Math.sin(halfPitch);
  4549. var cosPitch = Math.cos(halfPitch);
  4550. var sinYaw = Math.sin(halfYaw);
  4551. var cosYaw = Math.cos(halfYaw);
  4552. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4553. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4554. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4555. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4556. };
  4557. /**
  4558. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4559. */
  4560. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4561. var result = new Quaternion();
  4562. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4563. return result;
  4564. };
  4565. /**
  4566. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4567. */
  4568. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4569. // Produces a quaternion from Euler angles in the z-x-z orientation
  4570. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4571. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4572. var halfBeta = beta * 0.5;
  4573. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4574. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4575. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4576. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4577. };
  4578. /**
  4579. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4580. * cf to Vector3.RotationFromAxis() documentation.
  4581. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4582. */
  4583. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4584. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4585. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4586. return quat;
  4587. };
  4588. /**
  4589. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4590. * cf to Vector3.RotationFromAxis() documentation.
  4591. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4592. */
  4593. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4594. var rotMat = MathTmp.Matrix[0];
  4595. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4596. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4597. };
  4598. Quaternion.Slerp = function (left, right, amount) {
  4599. var result = Quaternion.Identity();
  4600. Quaternion.SlerpToRef(left, right, amount, result);
  4601. return result;
  4602. };
  4603. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4604. var num2;
  4605. var num3;
  4606. var num = amount;
  4607. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4608. var flag = false;
  4609. if (num4 < 0) {
  4610. flag = true;
  4611. num4 = -num4;
  4612. }
  4613. if (num4 > 0.999999) {
  4614. num3 = 1 - num;
  4615. num2 = flag ? -num : num;
  4616. }
  4617. else {
  4618. var num5 = Math.acos(num4);
  4619. var num6 = (1.0 / Math.sin(num5));
  4620. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4621. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4622. }
  4623. result.x = (num3 * left.x) + (num2 * right.x);
  4624. result.y = (num3 * left.y) + (num2 * right.y);
  4625. result.z = (num3 * left.z) + (num2 * right.z);
  4626. result.w = (num3 * left.w) + (num2 * right.w);
  4627. };
  4628. /**
  4629. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4630. */
  4631. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4632. var squared = amount * amount;
  4633. var cubed = amount * squared;
  4634. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4635. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4636. var part3 = (cubed - (2.0 * squared)) + amount;
  4637. var part4 = cubed - squared;
  4638. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4639. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4640. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4641. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4642. return new Quaternion(x, y, z, w);
  4643. };
  4644. return Quaternion;
  4645. }());
  4646. BABYLON.Quaternion = Quaternion;
  4647. var Matrix = /** @class */ (function () {
  4648. function Matrix() {
  4649. this._isIdentity = false;
  4650. this._isIdentityDirty = true;
  4651. this.m = new Float32Array(16);
  4652. this._markAsUpdated();
  4653. }
  4654. Matrix.prototype._markAsUpdated = function () {
  4655. this.updateFlag = Matrix._updateFlagSeed++;
  4656. this._isIdentityDirty = true;
  4657. };
  4658. // Properties
  4659. /**
  4660. * Boolean : True is the matrix is the identity matrix
  4661. */
  4662. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4663. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4664. if (this._isIdentityDirty) {
  4665. this._isIdentityDirty = false;
  4666. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4667. this._isIdentity = false;
  4668. }
  4669. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4670. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4671. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4672. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4673. this._isIdentity = false;
  4674. }
  4675. else {
  4676. this._isIdentity = true;
  4677. }
  4678. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4679. this._isIdentity = false;
  4680. }
  4681. }
  4682. return this._isIdentity;
  4683. };
  4684. /**
  4685. * Returns the matrix determinant (float).
  4686. */
  4687. Matrix.prototype.determinant = function () {
  4688. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4689. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4690. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4691. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4692. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4693. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4694. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4695. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4696. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4697. };
  4698. // Methods
  4699. /**
  4700. * Returns the matrix underlying array.
  4701. */
  4702. Matrix.prototype.toArray = function () {
  4703. return this.m;
  4704. };
  4705. /**
  4706. * Returns the matrix underlying array.
  4707. */
  4708. Matrix.prototype.asArray = function () {
  4709. return this.toArray();
  4710. };
  4711. /**
  4712. * Inverts in place the Matrix.
  4713. * Returns the Matrix inverted.
  4714. */
  4715. Matrix.prototype.invert = function () {
  4716. this.invertToRef(this);
  4717. return this;
  4718. };
  4719. /**
  4720. * Sets all the matrix elements to zero.
  4721. * Returns the Matrix.
  4722. */
  4723. Matrix.prototype.reset = function () {
  4724. for (var index = 0; index < 16; index++) {
  4725. this.m[index] = 0.0;
  4726. }
  4727. this._markAsUpdated();
  4728. return this;
  4729. };
  4730. /**
  4731. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4732. */
  4733. Matrix.prototype.add = function (other) {
  4734. var result = new Matrix();
  4735. this.addToRef(other, result);
  4736. return result;
  4737. };
  4738. /**
  4739. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4740. * Returns the Matrix.
  4741. */
  4742. Matrix.prototype.addToRef = function (other, result) {
  4743. for (var index = 0; index < 16; index++) {
  4744. result.m[index] = this.m[index] + other.m[index];
  4745. }
  4746. result._markAsUpdated();
  4747. return this;
  4748. };
  4749. /**
  4750. * Adds in place the passed matrix to the current Matrix.
  4751. * Returns the updated Matrix.
  4752. */
  4753. Matrix.prototype.addToSelf = function (other) {
  4754. for (var index = 0; index < 16; index++) {
  4755. this.m[index] += other.m[index];
  4756. }
  4757. this._markAsUpdated();
  4758. return this;
  4759. };
  4760. /**
  4761. * Sets the passed matrix with the current inverted Matrix.
  4762. * Returns the unmodified current Matrix.
  4763. */
  4764. Matrix.prototype.invertToRef = function (other) {
  4765. var l1 = this.m[0];
  4766. var l2 = this.m[1];
  4767. var l3 = this.m[2];
  4768. var l4 = this.m[3];
  4769. var l5 = this.m[4];
  4770. var l6 = this.m[5];
  4771. var l7 = this.m[6];
  4772. var l8 = this.m[7];
  4773. var l9 = this.m[8];
  4774. var l10 = this.m[9];
  4775. var l11 = this.m[10];
  4776. var l12 = this.m[11];
  4777. var l13 = this.m[12];
  4778. var l14 = this.m[13];
  4779. var l15 = this.m[14];
  4780. var l16 = this.m[15];
  4781. var l17 = (l11 * l16) - (l12 * l15);
  4782. var l18 = (l10 * l16) - (l12 * l14);
  4783. var l19 = (l10 * l15) - (l11 * l14);
  4784. var l20 = (l9 * l16) - (l12 * l13);
  4785. var l21 = (l9 * l15) - (l11 * l13);
  4786. var l22 = (l9 * l14) - (l10 * l13);
  4787. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4788. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4789. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4790. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4791. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4792. var l28 = (l7 * l16) - (l8 * l15);
  4793. var l29 = (l6 * l16) - (l8 * l14);
  4794. var l30 = (l6 * l15) - (l7 * l14);
  4795. var l31 = (l5 * l16) - (l8 * l13);
  4796. var l32 = (l5 * l15) - (l7 * l13);
  4797. var l33 = (l5 * l14) - (l6 * l13);
  4798. var l34 = (l7 * l12) - (l8 * l11);
  4799. var l35 = (l6 * l12) - (l8 * l10);
  4800. var l36 = (l6 * l11) - (l7 * l10);
  4801. var l37 = (l5 * l12) - (l8 * l9);
  4802. var l38 = (l5 * l11) - (l7 * l9);
  4803. var l39 = (l5 * l10) - (l6 * l9);
  4804. other.m[0] = l23 * l27;
  4805. other.m[4] = l24 * l27;
  4806. other.m[8] = l25 * l27;
  4807. other.m[12] = l26 * l27;
  4808. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4809. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4810. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4811. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4812. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4813. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4814. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4815. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4816. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4817. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4818. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4819. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4820. other._markAsUpdated();
  4821. return this;
  4822. };
  4823. /**
  4824. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4825. * Returns the updated Matrix.
  4826. */
  4827. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4828. this.m[12] = x;
  4829. this.m[13] = y;
  4830. this.m[14] = z;
  4831. this._markAsUpdated();
  4832. return this;
  4833. };
  4834. /**
  4835. * Inserts the translation vector in the current Matrix.
  4836. * Returns the updated Matrix.
  4837. */
  4838. Matrix.prototype.setTranslation = function (vector3) {
  4839. this.m[12] = vector3.x;
  4840. this.m[13] = vector3.y;
  4841. this.m[14] = vector3.z;
  4842. this._markAsUpdated();
  4843. return this;
  4844. };
  4845. /**
  4846. * Returns a new Vector3 as the extracted translation from the Matrix.
  4847. */
  4848. Matrix.prototype.getTranslation = function () {
  4849. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4850. };
  4851. /**
  4852. * Fill a Vector3 with the extracted translation from the Matrix.
  4853. */
  4854. Matrix.prototype.getTranslationToRef = function (result) {
  4855. result.x = this.m[12];
  4856. result.y = this.m[13];
  4857. result.z = this.m[14];
  4858. return this;
  4859. };
  4860. /**
  4861. * Remove rotation and scaling part from the Matrix.
  4862. * Returns the updated Matrix.
  4863. */
  4864. Matrix.prototype.removeRotationAndScaling = function () {
  4865. this.setRowFromFloats(0, 1, 0, 0, 0);
  4866. this.setRowFromFloats(1, 0, 1, 0, 0);
  4867. this.setRowFromFloats(2, 0, 0, 1, 0);
  4868. return this;
  4869. };
  4870. /**
  4871. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4872. */
  4873. Matrix.prototype.multiply = function (other) {
  4874. var result = new Matrix();
  4875. this.multiplyToRef(other, result);
  4876. return result;
  4877. };
  4878. /**
  4879. * Updates the current Matrix from the passed one values.
  4880. * Returns the updated Matrix.
  4881. */
  4882. Matrix.prototype.copyFrom = function (other) {
  4883. for (var index = 0; index < 16; index++) {
  4884. this.m[index] = other.m[index];
  4885. }
  4886. this._markAsUpdated();
  4887. return this;
  4888. };
  4889. /**
  4890. * Populates the passed array from the starting index with the Matrix values.
  4891. * Returns the Matrix.
  4892. */
  4893. Matrix.prototype.copyToArray = function (array, offset) {
  4894. if (offset === void 0) { offset = 0; }
  4895. for (var index = 0; index < 16; index++) {
  4896. array[offset + index] = this.m[index];
  4897. }
  4898. return this;
  4899. };
  4900. /**
  4901. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4902. */
  4903. Matrix.prototype.multiplyToRef = function (other, result) {
  4904. this.multiplyToArray(other, result.m, 0);
  4905. result._markAsUpdated();
  4906. return this;
  4907. };
  4908. /**
  4909. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4910. */
  4911. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4912. var tm0 = this.m[0];
  4913. var tm1 = this.m[1];
  4914. var tm2 = this.m[2];
  4915. var tm3 = this.m[3];
  4916. var tm4 = this.m[4];
  4917. var tm5 = this.m[5];
  4918. var tm6 = this.m[6];
  4919. var tm7 = this.m[7];
  4920. var tm8 = this.m[8];
  4921. var tm9 = this.m[9];
  4922. var tm10 = this.m[10];
  4923. var tm11 = this.m[11];
  4924. var tm12 = this.m[12];
  4925. var tm13 = this.m[13];
  4926. var tm14 = this.m[14];
  4927. var tm15 = this.m[15];
  4928. var om0 = other.m[0];
  4929. var om1 = other.m[1];
  4930. var om2 = other.m[2];
  4931. var om3 = other.m[3];
  4932. var om4 = other.m[4];
  4933. var om5 = other.m[5];
  4934. var om6 = other.m[6];
  4935. var om7 = other.m[7];
  4936. var om8 = other.m[8];
  4937. var om9 = other.m[9];
  4938. var om10 = other.m[10];
  4939. var om11 = other.m[11];
  4940. var om12 = other.m[12];
  4941. var om13 = other.m[13];
  4942. var om14 = other.m[14];
  4943. var om15 = other.m[15];
  4944. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4945. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4946. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4947. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4948. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4949. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4950. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4951. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4952. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4953. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4954. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4955. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4956. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4957. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4958. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4959. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4960. return this;
  4961. };
  4962. /**
  4963. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4964. */
  4965. Matrix.prototype.equals = function (value) {
  4966. return value &&
  4967. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4968. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4969. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4970. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4971. };
  4972. /**
  4973. * Returns a new Matrix from the current Matrix.
  4974. */
  4975. Matrix.prototype.clone = function () {
  4976. 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]);
  4977. };
  4978. /**
  4979. * Returns the string "Matrix"
  4980. */
  4981. Matrix.prototype.getClassName = function () {
  4982. return "Matrix";
  4983. };
  4984. /**
  4985. * Returns the Matrix hash code.
  4986. */
  4987. Matrix.prototype.getHashCode = function () {
  4988. var hash = this.m[0] || 0;
  4989. for (var i = 1; i < 16; i++) {
  4990. hash = (hash * 397) ^ (this.m[i] || 0);
  4991. }
  4992. return hash;
  4993. };
  4994. /**
  4995. * Decomposes the current Matrix into :
  4996. * - a scale vector3 passed as a reference to update,
  4997. * - a rotation quaternion passed as a reference to update,
  4998. * - a translation vector3 passed as a reference to update.
  4999. * Returns the true if operation was successful.
  5000. */
  5001. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5002. translation.x = this.m[12];
  5003. translation.y = this.m[13];
  5004. translation.z = this.m[14];
  5005. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5006. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5007. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5008. if (this.determinant() <= 0) {
  5009. scale.y *= -1;
  5010. }
  5011. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5012. rotation.x = 0;
  5013. rotation.y = 0;
  5014. rotation.z = 0;
  5015. rotation.w = 1;
  5016. return false;
  5017. }
  5018. 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]);
  5019. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5020. return true;
  5021. };
  5022. /**
  5023. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5024. * @param ref matrix to store the result
  5025. */
  5026. Matrix.prototype.toNormalMatrix = function (ref) {
  5027. this.invertToRef(ref);
  5028. ref.transpose();
  5029. var m = ref.m;
  5030. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5031. };
  5032. /**
  5033. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5034. */
  5035. Matrix.prototype.getRotationMatrix = function () {
  5036. var result = Matrix.Identity();
  5037. this.getRotationMatrixToRef(result);
  5038. return result;
  5039. };
  5040. /**
  5041. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5042. * Returns the current Matrix.
  5043. */
  5044. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5045. var m = this.m;
  5046. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5047. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5048. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5049. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5050. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5051. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5052. 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);
  5053. return this;
  5054. };
  5055. // Statics
  5056. /**
  5057. * Returns a new Matrix set from the starting index of the passed array.
  5058. */
  5059. Matrix.FromArray = function (array, offset) {
  5060. var result = new Matrix();
  5061. if (!offset) {
  5062. offset = 0;
  5063. }
  5064. Matrix.FromArrayToRef(array, offset, result);
  5065. return result;
  5066. };
  5067. /**
  5068. * Sets the passed "result" matrix from the starting index of the passed array.
  5069. */
  5070. Matrix.FromArrayToRef = function (array, offset, result) {
  5071. for (var index = 0; index < 16; index++) {
  5072. result.m[index] = array[index + offset];
  5073. }
  5074. result._markAsUpdated();
  5075. };
  5076. /**
  5077. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5078. */
  5079. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5080. for (var index = 0; index < 16; index++) {
  5081. result.m[index] = array[index + offset] * scale;
  5082. }
  5083. result._markAsUpdated();
  5084. };
  5085. /**
  5086. * Sets the passed matrix "result" with the 16 passed floats.
  5087. */
  5088. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5089. result.m[0] = initialM11;
  5090. result.m[1] = initialM12;
  5091. result.m[2] = initialM13;
  5092. result.m[3] = initialM14;
  5093. result.m[4] = initialM21;
  5094. result.m[5] = initialM22;
  5095. result.m[6] = initialM23;
  5096. result.m[7] = initialM24;
  5097. result.m[8] = initialM31;
  5098. result.m[9] = initialM32;
  5099. result.m[10] = initialM33;
  5100. result.m[11] = initialM34;
  5101. result.m[12] = initialM41;
  5102. result.m[13] = initialM42;
  5103. result.m[14] = initialM43;
  5104. result.m[15] = initialM44;
  5105. result._markAsUpdated();
  5106. };
  5107. /**
  5108. * Returns the index-th row of the current matrix as a new Vector4.
  5109. */
  5110. Matrix.prototype.getRow = function (index) {
  5111. if (index < 0 || index > 3) {
  5112. return null;
  5113. }
  5114. var i = index * 4;
  5115. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5116. };
  5117. /**
  5118. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5119. * Returns the updated Matrix.
  5120. */
  5121. Matrix.prototype.setRow = function (index, row) {
  5122. if (index < 0 || index > 3) {
  5123. return this;
  5124. }
  5125. var i = index * 4;
  5126. this.m[i + 0] = row.x;
  5127. this.m[i + 1] = row.y;
  5128. this.m[i + 2] = row.z;
  5129. this.m[i + 3] = row.w;
  5130. this._markAsUpdated();
  5131. return this;
  5132. };
  5133. /**
  5134. * Compute the transpose of the matrix.
  5135. * Returns a new Matrix.
  5136. */
  5137. Matrix.prototype.transpose = function () {
  5138. return Matrix.Transpose(this);
  5139. };
  5140. /**
  5141. * Compute the transpose of the matrix.
  5142. * Returns the current matrix.
  5143. */
  5144. Matrix.prototype.transposeToRef = function (result) {
  5145. Matrix.TransposeToRef(this, result);
  5146. return this;
  5147. };
  5148. /**
  5149. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5150. * Returns the updated Matrix.
  5151. */
  5152. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5153. if (index < 0 || index > 3) {
  5154. return this;
  5155. }
  5156. var i = index * 4;
  5157. this.m[i + 0] = x;
  5158. this.m[i + 1] = y;
  5159. this.m[i + 2] = z;
  5160. this.m[i + 3] = w;
  5161. this._markAsUpdated();
  5162. return this;
  5163. };
  5164. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5165. /**
  5166. * Static identity matrix to be used as readonly matrix
  5167. * Must not be updated.
  5168. */
  5169. get: function () {
  5170. return Matrix._identityReadOnly;
  5171. },
  5172. enumerable: true,
  5173. configurable: true
  5174. });
  5175. /**
  5176. * Returns a new Matrix set from the 16 passed floats.
  5177. */
  5178. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5179. var result = new Matrix();
  5180. result.m[0] = initialM11;
  5181. result.m[1] = initialM12;
  5182. result.m[2] = initialM13;
  5183. result.m[3] = initialM14;
  5184. result.m[4] = initialM21;
  5185. result.m[5] = initialM22;
  5186. result.m[6] = initialM23;
  5187. result.m[7] = initialM24;
  5188. result.m[8] = initialM31;
  5189. result.m[9] = initialM32;
  5190. result.m[10] = initialM33;
  5191. result.m[11] = initialM34;
  5192. result.m[12] = initialM41;
  5193. result.m[13] = initialM42;
  5194. result.m[14] = initialM43;
  5195. result.m[15] = initialM44;
  5196. return result;
  5197. };
  5198. /**
  5199. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5200. */
  5201. Matrix.Compose = function (scale, rotation, translation) {
  5202. var result = Matrix.Identity();
  5203. Matrix.ComposeToRef(scale, rotation, translation, result);
  5204. return result;
  5205. };
  5206. /**
  5207. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5208. */
  5209. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5210. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5211. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5212. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5213. result.setTranslation(translation);
  5214. };
  5215. /**
  5216. * Returns a new indentity Matrix.
  5217. */
  5218. Matrix.Identity = function () {
  5219. 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);
  5220. };
  5221. /**
  5222. * Sets the passed "result" as an identity matrix.
  5223. */
  5224. Matrix.IdentityToRef = function (result) {
  5225. 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);
  5226. };
  5227. /**
  5228. * Returns a new zero Matrix.
  5229. */
  5230. Matrix.Zero = function () {
  5231. 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);
  5232. };
  5233. /**
  5234. * Returns a new rotation matrix for "angle" radians around the X axis.
  5235. */
  5236. Matrix.RotationX = function (angle) {
  5237. var result = new Matrix();
  5238. Matrix.RotationXToRef(angle, result);
  5239. return result;
  5240. };
  5241. /**
  5242. * Returns a new Matrix as the passed inverted one.
  5243. */
  5244. Matrix.Invert = function (source) {
  5245. var result = new Matrix();
  5246. source.invertToRef(result);
  5247. return result;
  5248. };
  5249. /**
  5250. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5251. */
  5252. Matrix.RotationXToRef = function (angle, result) {
  5253. var s = Math.sin(angle);
  5254. var c = Math.cos(angle);
  5255. result.m[0] = 1.0;
  5256. result.m[15] = 1.0;
  5257. result.m[5] = c;
  5258. result.m[10] = c;
  5259. result.m[9] = -s;
  5260. result.m[6] = s;
  5261. result.m[1] = 0.0;
  5262. result.m[2] = 0.0;
  5263. result.m[3] = 0.0;
  5264. result.m[4] = 0.0;
  5265. result.m[7] = 0.0;
  5266. result.m[8] = 0.0;
  5267. result.m[11] = 0.0;
  5268. result.m[12] = 0.0;
  5269. result.m[13] = 0.0;
  5270. result.m[14] = 0.0;
  5271. result._markAsUpdated();
  5272. };
  5273. /**
  5274. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5275. */
  5276. Matrix.RotationY = function (angle) {
  5277. var result = new Matrix();
  5278. Matrix.RotationYToRef(angle, result);
  5279. return result;
  5280. };
  5281. /**
  5282. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5283. */
  5284. Matrix.RotationYToRef = function (angle, result) {
  5285. var s = Math.sin(angle);
  5286. var c = Math.cos(angle);
  5287. result.m[5] = 1.0;
  5288. result.m[15] = 1.0;
  5289. result.m[0] = c;
  5290. result.m[2] = -s;
  5291. result.m[8] = s;
  5292. result.m[10] = c;
  5293. result.m[1] = 0.0;
  5294. result.m[3] = 0.0;
  5295. result.m[4] = 0.0;
  5296. result.m[6] = 0.0;
  5297. result.m[7] = 0.0;
  5298. result.m[9] = 0.0;
  5299. result.m[11] = 0.0;
  5300. result.m[12] = 0.0;
  5301. result.m[13] = 0.0;
  5302. result.m[14] = 0.0;
  5303. result._markAsUpdated();
  5304. };
  5305. /**
  5306. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5307. */
  5308. Matrix.RotationZ = function (angle) {
  5309. var result = new Matrix();
  5310. Matrix.RotationZToRef(angle, result);
  5311. return result;
  5312. };
  5313. /**
  5314. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5315. */
  5316. Matrix.RotationZToRef = function (angle, result) {
  5317. var s = Math.sin(angle);
  5318. var c = Math.cos(angle);
  5319. result.m[10] = 1.0;
  5320. result.m[15] = 1.0;
  5321. result.m[0] = c;
  5322. result.m[1] = s;
  5323. result.m[4] = -s;
  5324. result.m[5] = c;
  5325. result.m[2] = 0.0;
  5326. result.m[3] = 0.0;
  5327. result.m[6] = 0.0;
  5328. result.m[7] = 0.0;
  5329. result.m[8] = 0.0;
  5330. result.m[9] = 0.0;
  5331. result.m[11] = 0.0;
  5332. result.m[12] = 0.0;
  5333. result.m[13] = 0.0;
  5334. result.m[14] = 0.0;
  5335. result._markAsUpdated();
  5336. };
  5337. /**
  5338. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5339. */
  5340. Matrix.RotationAxis = function (axis, angle) {
  5341. var result = Matrix.Zero();
  5342. Matrix.RotationAxisToRef(axis, angle, result);
  5343. return result;
  5344. };
  5345. /**
  5346. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5347. */
  5348. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5349. var s = Math.sin(-angle);
  5350. var c = Math.cos(-angle);
  5351. var c1 = 1 - c;
  5352. axis.normalize();
  5353. result.m[0] = (axis.x * axis.x) * c1 + c;
  5354. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5355. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5356. result.m[3] = 0.0;
  5357. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5358. result.m[5] = (axis.y * axis.y) * c1 + c;
  5359. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5360. result.m[7] = 0.0;
  5361. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5362. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5363. result.m[10] = (axis.z * axis.z) * c1 + c;
  5364. result.m[11] = 0.0;
  5365. result.m[15] = 1.0;
  5366. result._markAsUpdated();
  5367. };
  5368. /**
  5369. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5370. */
  5371. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5372. var result = new Matrix();
  5373. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5374. return result;
  5375. };
  5376. /**
  5377. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5378. */
  5379. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5380. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5381. this._tempQuaternion.toRotationMatrix(result);
  5382. };
  5383. /**
  5384. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5385. */
  5386. Matrix.Scaling = function (x, y, z) {
  5387. var result = Matrix.Zero();
  5388. Matrix.ScalingToRef(x, y, z, result);
  5389. return result;
  5390. };
  5391. /**
  5392. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5393. */
  5394. Matrix.ScalingToRef = function (x, y, z, result) {
  5395. result.m[0] = x;
  5396. result.m[1] = 0.0;
  5397. result.m[2] = 0.0;
  5398. result.m[3] = 0.0;
  5399. result.m[4] = 0.0;
  5400. result.m[5] = y;
  5401. result.m[6] = 0.0;
  5402. result.m[7] = 0.0;
  5403. result.m[8] = 0.0;
  5404. result.m[9] = 0.0;
  5405. result.m[10] = z;
  5406. result.m[11] = 0.0;
  5407. result.m[12] = 0.0;
  5408. result.m[13] = 0.0;
  5409. result.m[14] = 0.0;
  5410. result.m[15] = 1.0;
  5411. result._markAsUpdated();
  5412. };
  5413. /**
  5414. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5415. */
  5416. Matrix.Translation = function (x, y, z) {
  5417. var result = Matrix.Identity();
  5418. Matrix.TranslationToRef(x, y, z, result);
  5419. return result;
  5420. };
  5421. /**
  5422. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5423. */
  5424. Matrix.TranslationToRef = function (x, y, z, result) {
  5425. 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);
  5426. };
  5427. /**
  5428. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5429. * @param startValue defines the start value
  5430. * @param endValue defines the end value
  5431. * @param gradient defines the gradient factor
  5432. * @returns the new matrix
  5433. */
  5434. Matrix.Lerp = function (startValue, endValue, gradient) {
  5435. var result = Matrix.Zero();
  5436. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5437. return result;
  5438. };
  5439. /**
  5440. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5441. * @param startValue defines the start value
  5442. * @param endValue defines the end value
  5443. * @param gradient defines the gradient factor
  5444. * @param result defines the Matrix object where to store data
  5445. */
  5446. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5447. for (var index = 0; index < 16; index++) {
  5448. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5449. }
  5450. result._markAsUpdated();
  5451. };
  5452. /**
  5453. * Returns a new Matrix whose values are computed by :
  5454. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5455. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5456. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5457. */
  5458. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5459. var startScale = new Vector3(0, 0, 0);
  5460. var startRotation = new Quaternion();
  5461. var startTranslation = new Vector3(0, 0, 0);
  5462. startValue.decompose(startScale, startRotation, startTranslation);
  5463. var endScale = new Vector3(0, 0, 0);
  5464. var endRotation = new Quaternion();
  5465. var endTranslation = new Vector3(0, 0, 0);
  5466. endValue.decompose(endScale, endRotation, endTranslation);
  5467. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5468. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5469. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5470. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5471. };
  5472. /**
  5473. * 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".
  5474. * This methods works for a Left-Handed system.
  5475. */
  5476. Matrix.LookAtLH = function (eye, target, up) {
  5477. var result = Matrix.Zero();
  5478. Matrix.LookAtLHToRef(eye, target, up, result);
  5479. return result;
  5480. };
  5481. /**
  5482. * 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".
  5483. * This methods works for a Left-Handed system.
  5484. */
  5485. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5486. // Z axis
  5487. target.subtractToRef(eye, this._zAxis);
  5488. this._zAxis.normalize();
  5489. // X axis
  5490. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5491. if (this._xAxis.lengthSquared() === 0) {
  5492. this._xAxis.x = 1.0;
  5493. }
  5494. else {
  5495. this._xAxis.normalize();
  5496. }
  5497. // Y axis
  5498. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5499. this._yAxis.normalize();
  5500. // Eye angles
  5501. var ex = -Vector3.Dot(this._xAxis, eye);
  5502. var ey = -Vector3.Dot(this._yAxis, eye);
  5503. var ez = -Vector3.Dot(this._zAxis, eye);
  5504. 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);
  5505. };
  5506. /**
  5507. * 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".
  5508. * This methods works for a Right-Handed system.
  5509. */
  5510. Matrix.LookAtRH = function (eye, target, up) {
  5511. var result = Matrix.Zero();
  5512. Matrix.LookAtRHToRef(eye, target, up, result);
  5513. return result;
  5514. };
  5515. /**
  5516. * 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".
  5517. * This methods works for a Left-Handed system.
  5518. */
  5519. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5520. // Z axis
  5521. eye.subtractToRef(target, this._zAxis);
  5522. this._zAxis.normalize();
  5523. // X axis
  5524. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5525. if (this._xAxis.lengthSquared() === 0) {
  5526. this._xAxis.x = 1.0;
  5527. }
  5528. else {
  5529. this._xAxis.normalize();
  5530. }
  5531. // Y axis
  5532. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5533. this._yAxis.normalize();
  5534. // Eye angles
  5535. var ex = -Vector3.Dot(this._xAxis, eye);
  5536. var ey = -Vector3.Dot(this._yAxis, eye);
  5537. var ez = -Vector3.Dot(this._zAxis, eye);
  5538. 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);
  5539. };
  5540. /**
  5541. * 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.
  5542. */
  5543. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5544. var matrix = Matrix.Zero();
  5545. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5546. return matrix;
  5547. };
  5548. /**
  5549. * 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.
  5550. */
  5551. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5552. var n = znear;
  5553. var f = zfar;
  5554. var a = 2.0 / width;
  5555. var b = 2.0 / height;
  5556. var c = 2.0 / (f - n);
  5557. var d = -(f + n) / (f - n);
  5558. 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);
  5559. };
  5560. /**
  5561. * 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.
  5562. */
  5563. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5564. var matrix = Matrix.Zero();
  5565. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5566. return matrix;
  5567. };
  5568. /**
  5569. * 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.
  5570. */
  5571. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5572. var n = znear;
  5573. var f = zfar;
  5574. var a = 2.0 / (right - left);
  5575. var b = 2.0 / (top - bottom);
  5576. var c = 2.0 / (f - n);
  5577. var d = -(f + n) / (f - n);
  5578. var i0 = (left + right) / (left - right);
  5579. var i1 = (top + bottom) / (bottom - top);
  5580. 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);
  5581. };
  5582. /**
  5583. * 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.
  5584. */
  5585. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5586. var matrix = Matrix.Zero();
  5587. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5588. return matrix;
  5589. };
  5590. /**
  5591. * 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.
  5592. */
  5593. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5594. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5595. result.m[10] *= -1.0;
  5596. };
  5597. /**
  5598. * 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.
  5599. */
  5600. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5601. var matrix = Matrix.Zero();
  5602. var n = znear;
  5603. var f = zfar;
  5604. var a = 2.0 * n / width;
  5605. var b = 2.0 * n / height;
  5606. var c = (f + n) / (f - n);
  5607. var d = -2.0 * f * n / (f - n);
  5608. 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);
  5609. return matrix;
  5610. };
  5611. /**
  5612. * 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.
  5613. */
  5614. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5615. var matrix = Matrix.Zero();
  5616. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5617. return matrix;
  5618. };
  5619. /**
  5620. * 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.
  5621. */
  5622. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5623. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5624. var n = znear;
  5625. var f = zfar;
  5626. var t = 1.0 / (Math.tan(fov * 0.5));
  5627. var a = isVerticalFovFixed ? (t / aspect) : t;
  5628. var b = isVerticalFovFixed ? t : (t * aspect);
  5629. var c = (f + n) / (f - n);
  5630. var d = -2.0 * f * n / (f - n);
  5631. 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);
  5632. };
  5633. /**
  5634. * 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.
  5635. */
  5636. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5637. var matrix = Matrix.Zero();
  5638. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5639. return matrix;
  5640. };
  5641. /**
  5642. * 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.
  5643. */
  5644. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5645. //alternatively this could be expressed as:
  5646. // m = PerspectiveFovLHToRef
  5647. // m[10] *= -1.0;
  5648. // m[11] *= -1.0;
  5649. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5650. var n = znear;
  5651. var f = zfar;
  5652. var t = 1.0 / (Math.tan(fov * 0.5));
  5653. var a = isVerticalFovFixed ? (t / aspect) : t;
  5654. var b = isVerticalFovFixed ? t : (t * aspect);
  5655. var c = -(f + n) / (f - n);
  5656. var d = -2 * f * n / (f - n);
  5657. 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);
  5658. };
  5659. /**
  5660. * 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.
  5661. */
  5662. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5663. if (rightHanded === void 0) { rightHanded = false; }
  5664. var rightHandedFactor = rightHanded ? -1 : 1;
  5665. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5666. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5667. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5668. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5669. var xScale = 2.0 / (leftTan + rightTan);
  5670. var yScale = 2.0 / (upTan + downTan);
  5671. result.m[0] = xScale;
  5672. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5673. result.m[5] = yScale;
  5674. result.m[6] = result.m[7] = 0.0;
  5675. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5676. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5677. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5678. result.m[10] = -zfar / (znear - zfar);
  5679. result.m[11] = 1.0 * rightHandedFactor;
  5680. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5681. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5682. // result.m[14] = (znear * zfar) / (znear - zfar);
  5683. result._markAsUpdated();
  5684. };
  5685. /**
  5686. * Returns the final transformation matrix : world * view * projection * viewport
  5687. */
  5688. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5689. var cw = viewport.width;
  5690. var ch = viewport.height;
  5691. var cx = viewport.x;
  5692. var cy = viewport.y;
  5693. 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);
  5694. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5695. };
  5696. /**
  5697. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5698. */
  5699. Matrix.GetAsMatrix2x2 = function (matrix) {
  5700. return new Float32Array([
  5701. matrix.m[0], matrix.m[1],
  5702. matrix.m[4], matrix.m[5]
  5703. ]);
  5704. };
  5705. /**
  5706. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5707. */
  5708. Matrix.GetAsMatrix3x3 = function (matrix) {
  5709. return new Float32Array([
  5710. matrix.m[0], matrix.m[1], matrix.m[2],
  5711. matrix.m[4], matrix.m[5], matrix.m[6],
  5712. matrix.m[8], matrix.m[9], matrix.m[10]
  5713. ]);
  5714. };
  5715. /**
  5716. * Compute the transpose of the passed Matrix.
  5717. * Returns a new Matrix.
  5718. */
  5719. Matrix.Transpose = function (matrix) {
  5720. var result = new Matrix();
  5721. Matrix.TransposeToRef(matrix, result);
  5722. return result;
  5723. };
  5724. /**
  5725. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5726. */
  5727. Matrix.TransposeToRef = function (matrix, result) {
  5728. result.m[0] = matrix.m[0];
  5729. result.m[1] = matrix.m[4];
  5730. result.m[2] = matrix.m[8];
  5731. result.m[3] = matrix.m[12];
  5732. result.m[4] = matrix.m[1];
  5733. result.m[5] = matrix.m[5];
  5734. result.m[6] = matrix.m[9];
  5735. result.m[7] = matrix.m[13];
  5736. result.m[8] = matrix.m[2];
  5737. result.m[9] = matrix.m[6];
  5738. result.m[10] = matrix.m[10];
  5739. result.m[11] = matrix.m[14];
  5740. result.m[12] = matrix.m[3];
  5741. result.m[13] = matrix.m[7];
  5742. result.m[14] = matrix.m[11];
  5743. result.m[15] = matrix.m[15];
  5744. };
  5745. /**
  5746. * Returns a new Matrix as the reflection matrix across the passed plane.
  5747. */
  5748. Matrix.Reflection = function (plane) {
  5749. var matrix = new Matrix();
  5750. Matrix.ReflectionToRef(plane, matrix);
  5751. return matrix;
  5752. };
  5753. /**
  5754. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5755. */
  5756. Matrix.ReflectionToRef = function (plane, result) {
  5757. plane.normalize();
  5758. var x = plane.normal.x;
  5759. var y = plane.normal.y;
  5760. var z = plane.normal.z;
  5761. var temp = -2 * x;
  5762. var temp2 = -2 * y;
  5763. var temp3 = -2 * z;
  5764. result.m[0] = (temp * x) + 1;
  5765. result.m[1] = temp2 * x;
  5766. result.m[2] = temp3 * x;
  5767. result.m[3] = 0.0;
  5768. result.m[4] = temp * y;
  5769. result.m[5] = (temp2 * y) + 1;
  5770. result.m[6] = temp3 * y;
  5771. result.m[7] = 0.0;
  5772. result.m[8] = temp * z;
  5773. result.m[9] = temp2 * z;
  5774. result.m[10] = (temp3 * z) + 1;
  5775. result.m[11] = 0.0;
  5776. result.m[12] = temp * plane.d;
  5777. result.m[13] = temp2 * plane.d;
  5778. result.m[14] = temp3 * plane.d;
  5779. result.m[15] = 1.0;
  5780. result._markAsUpdated();
  5781. };
  5782. /**
  5783. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5784. */
  5785. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5786. result.m[0] = xaxis.x;
  5787. result.m[1] = xaxis.y;
  5788. result.m[2] = xaxis.z;
  5789. result.m[3] = 0.0;
  5790. result.m[4] = yaxis.x;
  5791. result.m[5] = yaxis.y;
  5792. result.m[6] = yaxis.z;
  5793. result.m[7] = 0.0;
  5794. result.m[8] = zaxis.x;
  5795. result.m[9] = zaxis.y;
  5796. result.m[10] = zaxis.z;
  5797. result.m[11] = 0.0;
  5798. result.m[12] = 0.0;
  5799. result.m[13] = 0.0;
  5800. result.m[14] = 0.0;
  5801. result.m[15] = 1.0;
  5802. result._markAsUpdated();
  5803. };
  5804. /**
  5805. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5806. */
  5807. Matrix.FromQuaternionToRef = function (quat, result) {
  5808. var xx = quat.x * quat.x;
  5809. var yy = quat.y * quat.y;
  5810. var zz = quat.z * quat.z;
  5811. var xy = quat.x * quat.y;
  5812. var zw = quat.z * quat.w;
  5813. var zx = quat.z * quat.x;
  5814. var yw = quat.y * quat.w;
  5815. var yz = quat.y * quat.z;
  5816. var xw = quat.x * quat.w;
  5817. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5818. result.m[1] = 2.0 * (xy + zw);
  5819. result.m[2] = 2.0 * (zx - yw);
  5820. result.m[3] = 0.0;
  5821. result.m[4] = 2.0 * (xy - zw);
  5822. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5823. result.m[6] = 2.0 * (yz + xw);
  5824. result.m[7] = 0.0;
  5825. result.m[8] = 2.0 * (zx + yw);
  5826. result.m[9] = 2.0 * (yz - xw);
  5827. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5828. result.m[11] = 0.0;
  5829. result.m[12] = 0.0;
  5830. result.m[13] = 0.0;
  5831. result.m[14] = 0.0;
  5832. result.m[15] = 1.0;
  5833. result._markAsUpdated();
  5834. };
  5835. Matrix._tempQuaternion = new Quaternion();
  5836. Matrix._xAxis = Vector3.Zero();
  5837. Matrix._yAxis = Vector3.Zero();
  5838. Matrix._zAxis = Vector3.Zero();
  5839. Matrix._updateFlagSeed = 0;
  5840. Matrix._identityReadOnly = Matrix.Identity();
  5841. return Matrix;
  5842. }());
  5843. BABYLON.Matrix = Matrix;
  5844. var Plane = /** @class */ (function () {
  5845. /**
  5846. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5847. */
  5848. function Plane(a, b, c, d) {
  5849. this.normal = new Vector3(a, b, c);
  5850. this.d = d;
  5851. }
  5852. /**
  5853. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5854. */
  5855. Plane.prototype.asArray = function () {
  5856. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5857. };
  5858. // Methods
  5859. /**
  5860. * Returns a new plane copied from the current Plane.
  5861. */
  5862. Plane.prototype.clone = function () {
  5863. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5864. };
  5865. /**
  5866. * Returns the string "Plane".
  5867. */
  5868. Plane.prototype.getClassName = function () {
  5869. return "Plane";
  5870. };
  5871. /**
  5872. * Returns the Plane hash code.
  5873. */
  5874. Plane.prototype.getHashCode = function () {
  5875. var hash = this.normal.getHashCode();
  5876. hash = (hash * 397) ^ (this.d || 0);
  5877. return hash;
  5878. };
  5879. /**
  5880. * Normalize the current Plane in place.
  5881. * Returns the updated Plane.
  5882. */
  5883. Plane.prototype.normalize = function () {
  5884. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5885. var magnitude = 0.0;
  5886. if (norm !== 0) {
  5887. magnitude = 1.0 / norm;
  5888. }
  5889. this.normal.x *= magnitude;
  5890. this.normal.y *= magnitude;
  5891. this.normal.z *= magnitude;
  5892. this.d *= magnitude;
  5893. return this;
  5894. };
  5895. /**
  5896. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5897. */
  5898. Plane.prototype.transform = function (transformation) {
  5899. var transposedMatrix = Matrix.Transpose(transformation);
  5900. var x = this.normal.x;
  5901. var y = this.normal.y;
  5902. var z = this.normal.z;
  5903. var d = this.d;
  5904. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5905. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5906. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5907. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5908. return new Plane(normalX, normalY, normalZ, finalD);
  5909. };
  5910. /**
  5911. * Returns the dot product (float) of the point coordinates and the plane normal.
  5912. */
  5913. Plane.prototype.dotCoordinate = function (point) {
  5914. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5915. };
  5916. /**
  5917. * Updates the current Plane from the plane defined by the three passed points.
  5918. * Returns the updated Plane.
  5919. */
  5920. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5921. var x1 = point2.x - point1.x;
  5922. var y1 = point2.y - point1.y;
  5923. var z1 = point2.z - point1.z;
  5924. var x2 = point3.x - point1.x;
  5925. var y2 = point3.y - point1.y;
  5926. var z2 = point3.z - point1.z;
  5927. var yz = (y1 * z2) - (z1 * y2);
  5928. var xz = (z1 * x2) - (x1 * z2);
  5929. var xy = (x1 * y2) - (y1 * x2);
  5930. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5931. var invPyth;
  5932. if (pyth !== 0) {
  5933. invPyth = 1.0 / pyth;
  5934. }
  5935. else {
  5936. invPyth = 0.0;
  5937. }
  5938. this.normal.x = yz * invPyth;
  5939. this.normal.y = xz * invPyth;
  5940. this.normal.z = xy * invPyth;
  5941. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5942. return this;
  5943. };
  5944. /**
  5945. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5946. */
  5947. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5948. var dot = Vector3.Dot(this.normal, direction);
  5949. return (dot <= epsilon);
  5950. };
  5951. /**
  5952. * Returns the signed distance (float) from the passed point to the Plane.
  5953. */
  5954. Plane.prototype.signedDistanceTo = function (point) {
  5955. return Vector3.Dot(point, this.normal) + this.d;
  5956. };
  5957. // Statics
  5958. /**
  5959. * Returns a new Plane from the passed array.
  5960. */
  5961. Plane.FromArray = function (array) {
  5962. return new Plane(array[0], array[1], array[2], array[3]);
  5963. };
  5964. /**
  5965. * Returns a new Plane defined by the three passed points.
  5966. */
  5967. Plane.FromPoints = function (point1, point2, point3) {
  5968. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5969. result.copyFromPoints(point1, point2, point3);
  5970. return result;
  5971. };
  5972. /**
  5973. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5974. * Note : the vector "normal" is updated because normalized.
  5975. */
  5976. Plane.FromPositionAndNormal = function (origin, normal) {
  5977. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5978. normal.normalize();
  5979. result.normal = normal;
  5980. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5981. return result;
  5982. };
  5983. /**
  5984. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5985. */
  5986. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5987. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5988. return Vector3.Dot(point, normal) + d;
  5989. };
  5990. return Plane;
  5991. }());
  5992. BABYLON.Plane = Plane;
  5993. var Viewport = /** @class */ (function () {
  5994. /**
  5995. * Creates a Viewport object located at (x, y) and sized (width, height).
  5996. */
  5997. function Viewport(x, y, width, height) {
  5998. this.x = x;
  5999. this.y = y;
  6000. this.width = width;
  6001. this.height = height;
  6002. }
  6003. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6004. if (renderWidthOrEngine.getRenderWidth) {
  6005. var engine = renderWidthOrEngine;
  6006. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6007. }
  6008. var renderWidth = renderWidthOrEngine;
  6009. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6010. };
  6011. /**
  6012. * Returns a new Viewport copied from the current one.
  6013. */
  6014. Viewport.prototype.clone = function () {
  6015. return new Viewport(this.x, this.y, this.width, this.height);
  6016. };
  6017. return Viewport;
  6018. }());
  6019. BABYLON.Viewport = Viewport;
  6020. var Frustum = /** @class */ (function () {
  6021. function Frustum() {
  6022. }
  6023. /**
  6024. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6025. */
  6026. Frustum.GetPlanes = function (transform) {
  6027. var frustumPlanes = [];
  6028. for (var index = 0; index < 6; index++) {
  6029. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6030. }
  6031. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6032. return frustumPlanes;
  6033. };
  6034. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6035. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6036. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6037. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6038. frustumPlane.d = transform.m[15] + transform.m[14];
  6039. frustumPlane.normalize();
  6040. };
  6041. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6042. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6043. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6044. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6045. frustumPlane.d = transform.m[15] - transform.m[14];
  6046. frustumPlane.normalize();
  6047. };
  6048. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6049. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6050. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6051. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6052. frustumPlane.d = transform.m[15] + transform.m[12];
  6053. frustumPlane.normalize();
  6054. };
  6055. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6056. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6057. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6058. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6059. frustumPlane.d = transform.m[15] - transform.m[12];
  6060. frustumPlane.normalize();
  6061. };
  6062. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6063. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6064. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6065. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6066. frustumPlane.d = transform.m[15] - transform.m[13];
  6067. frustumPlane.normalize();
  6068. };
  6069. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6070. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6071. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6072. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6073. frustumPlane.d = transform.m[15] + transform.m[13];
  6074. frustumPlane.normalize();
  6075. };
  6076. /**
  6077. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6078. */
  6079. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6080. // Near
  6081. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6082. // Far
  6083. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6084. // Left
  6085. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6086. // Right
  6087. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6088. // Top
  6089. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6090. // Bottom
  6091. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6092. };
  6093. return Frustum;
  6094. }());
  6095. BABYLON.Frustum = Frustum;
  6096. var Space;
  6097. (function (Space) {
  6098. Space[Space["LOCAL"] = 0] = "LOCAL";
  6099. Space[Space["WORLD"] = 1] = "WORLD";
  6100. Space[Space["BONE"] = 2] = "BONE";
  6101. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6102. var Axis = /** @class */ (function () {
  6103. function Axis() {
  6104. }
  6105. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6106. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6107. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6108. return Axis;
  6109. }());
  6110. BABYLON.Axis = Axis;
  6111. ;
  6112. var BezierCurve = /** @class */ (function () {
  6113. function BezierCurve() {
  6114. }
  6115. /**
  6116. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6117. */
  6118. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6119. // Extract X (which is equal to time here)
  6120. var f0 = 1 - 3 * x2 + 3 * x1;
  6121. var f1 = 3 * x2 - 6 * x1;
  6122. var f2 = 3 * x1;
  6123. var refinedT = t;
  6124. for (var i = 0; i < 5; i++) {
  6125. var refinedT2 = refinedT * refinedT;
  6126. var refinedT3 = refinedT2 * refinedT;
  6127. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6128. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6129. refinedT -= (x - t) * slope;
  6130. refinedT = Math.min(1, Math.max(0, refinedT));
  6131. }
  6132. // Resolve cubic bezier for the given x
  6133. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6134. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6135. Math.pow(refinedT, 3);
  6136. };
  6137. return BezierCurve;
  6138. }());
  6139. BABYLON.BezierCurve = BezierCurve;
  6140. var Orientation;
  6141. (function (Orientation) {
  6142. Orientation[Orientation["CW"] = 0] = "CW";
  6143. Orientation[Orientation["CCW"] = 1] = "CCW";
  6144. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6145. var Angle = /** @class */ (function () {
  6146. /**
  6147. * Creates an Angle object of "radians" radians (float).
  6148. */
  6149. function Angle(radians) {
  6150. var _this = this;
  6151. /**
  6152. * Returns the Angle value in degrees (float).
  6153. */
  6154. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6155. /**
  6156. * Returns the Angle value in radians (float).
  6157. */
  6158. this.radians = function () { return _this._radians; };
  6159. this._radians = radians;
  6160. if (this._radians < 0.0)
  6161. this._radians += (2.0 * Math.PI);
  6162. }
  6163. /**
  6164. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6165. */
  6166. Angle.BetweenTwoPoints = function (a, b) {
  6167. var delta = b.subtract(a);
  6168. var theta = Math.atan2(delta.y, delta.x);
  6169. return new Angle(theta);
  6170. };
  6171. /**
  6172. * Returns a new Angle object from the passed float in radians.
  6173. */
  6174. Angle.FromRadians = function (radians) {
  6175. return new Angle(radians);
  6176. };
  6177. /**
  6178. * Returns a new Angle object from the passed float in degrees.
  6179. */
  6180. Angle.FromDegrees = function (degrees) {
  6181. return new Angle(degrees * Math.PI / 180.0);
  6182. };
  6183. return Angle;
  6184. }());
  6185. BABYLON.Angle = Angle;
  6186. var Arc2 = /** @class */ (function () {
  6187. /**
  6188. * Creates an Arc object from the three passed points : start, middle and end.
  6189. */
  6190. function Arc2(startPoint, midPoint, endPoint) {
  6191. this.startPoint = startPoint;
  6192. this.midPoint = midPoint;
  6193. this.endPoint = endPoint;
  6194. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6195. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6196. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6197. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6198. 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);
  6199. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6200. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6201. var a1 = this.startAngle.degrees();
  6202. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6203. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6204. // angles correction
  6205. if (a2 - a1 > +180.0)
  6206. a2 -= 360.0;
  6207. if (a2 - a1 < -180.0)
  6208. a2 += 360.0;
  6209. if (a3 - a2 > +180.0)
  6210. a3 -= 360.0;
  6211. if (a3 - a2 < -180.0)
  6212. a3 += 360.0;
  6213. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6214. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6215. }
  6216. return Arc2;
  6217. }());
  6218. BABYLON.Arc2 = Arc2;
  6219. var Path2 = /** @class */ (function () {
  6220. /**
  6221. * Creates a Path2 object from the starting 2D coordinates x and y.
  6222. */
  6223. function Path2(x, y) {
  6224. this._points = new Array();
  6225. this._length = 0.0;
  6226. this.closed = false;
  6227. this._points.push(new Vector2(x, y));
  6228. }
  6229. /**
  6230. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6231. * Returns the updated Path2.
  6232. */
  6233. Path2.prototype.addLineTo = function (x, y) {
  6234. if (this.closed) {
  6235. return this;
  6236. }
  6237. var newPoint = new Vector2(x, y);
  6238. var previousPoint = this._points[this._points.length - 1];
  6239. this._points.push(newPoint);
  6240. this._length += newPoint.subtract(previousPoint).length();
  6241. return this;
  6242. };
  6243. /**
  6244. * 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.
  6245. * Returns the updated Path2.
  6246. */
  6247. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6248. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6249. if (this.closed) {
  6250. return this;
  6251. }
  6252. var startPoint = this._points[this._points.length - 1];
  6253. var midPoint = new Vector2(midX, midY);
  6254. var endPoint = new Vector2(endX, endY);
  6255. var arc = new Arc2(startPoint, midPoint, endPoint);
  6256. var increment = arc.angle.radians() / numberOfSegments;
  6257. if (arc.orientation === Orientation.CW)
  6258. increment *= -1;
  6259. var currentAngle = arc.startAngle.radians() + increment;
  6260. for (var i = 0; i < numberOfSegments; i++) {
  6261. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6262. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6263. this.addLineTo(x, y);
  6264. currentAngle += increment;
  6265. }
  6266. return this;
  6267. };
  6268. /**
  6269. * Closes the Path2.
  6270. * Returns the Path2.
  6271. */
  6272. Path2.prototype.close = function () {
  6273. this.closed = true;
  6274. return this;
  6275. };
  6276. /**
  6277. * Returns the Path2 total length (float).
  6278. */
  6279. Path2.prototype.length = function () {
  6280. var result = this._length;
  6281. if (!this.closed) {
  6282. var lastPoint = this._points[this._points.length - 1];
  6283. var firstPoint = this._points[0];
  6284. result += (firstPoint.subtract(lastPoint).length());
  6285. }
  6286. return result;
  6287. };
  6288. /**
  6289. * Returns the Path2 internal array of points.
  6290. */
  6291. Path2.prototype.getPoints = function () {
  6292. return this._points;
  6293. };
  6294. /**
  6295. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6296. */
  6297. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6298. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6299. return Vector2.Zero();
  6300. }
  6301. var lengthPosition = normalizedLengthPosition * this.length();
  6302. var previousOffset = 0;
  6303. for (var i = 0; i < this._points.length; i++) {
  6304. var j = (i + 1) % this._points.length;
  6305. var a = this._points[i];
  6306. var b = this._points[j];
  6307. var bToA = b.subtract(a);
  6308. var nextOffset = (bToA.length() + previousOffset);
  6309. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6310. var dir = bToA.normalize();
  6311. var localOffset = lengthPosition - previousOffset;
  6312. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6313. }
  6314. previousOffset = nextOffset;
  6315. }
  6316. return Vector2.Zero();
  6317. };
  6318. /**
  6319. * Returns a new Path2 starting at the coordinates (x, y).
  6320. */
  6321. Path2.StartingAt = function (x, y) {
  6322. return new Path2(x, y);
  6323. };
  6324. return Path2;
  6325. }());
  6326. BABYLON.Path2 = Path2;
  6327. var Path3D = /** @class */ (function () {
  6328. /**
  6329. * new Path3D(path, normal, raw)
  6330. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6331. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6332. * path : an array of Vector3, the curve axis of the Path3D
  6333. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6334. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6335. */
  6336. function Path3D(path, firstNormal, raw) {
  6337. if (firstNormal === void 0) { firstNormal = null; }
  6338. this.path = path;
  6339. this._curve = new Array();
  6340. this._distances = new Array();
  6341. this._tangents = new Array();
  6342. this._normals = new Array();
  6343. this._binormals = new Array();
  6344. for (var p = 0; p < path.length; p++) {
  6345. this._curve[p] = path[p].clone(); // hard copy
  6346. }
  6347. this._raw = raw || false;
  6348. this._compute(firstNormal);
  6349. }
  6350. /**
  6351. * Returns the Path3D array of successive Vector3 designing its curve.
  6352. */
  6353. Path3D.prototype.getCurve = function () {
  6354. return this._curve;
  6355. };
  6356. /**
  6357. * Returns an array populated with tangent vectors on each Path3D curve point.
  6358. */
  6359. Path3D.prototype.getTangents = function () {
  6360. return this._tangents;
  6361. };
  6362. /**
  6363. * Returns an array populated with normal vectors on each Path3D curve point.
  6364. */
  6365. Path3D.prototype.getNormals = function () {
  6366. return this._normals;
  6367. };
  6368. /**
  6369. * Returns an array populated with binormal vectors on each Path3D curve point.
  6370. */
  6371. Path3D.prototype.getBinormals = function () {
  6372. return this._binormals;
  6373. };
  6374. /**
  6375. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6376. */
  6377. Path3D.prototype.getDistances = function () {
  6378. return this._distances;
  6379. };
  6380. /**
  6381. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6382. * Returns the same object updated.
  6383. */
  6384. Path3D.prototype.update = function (path, firstNormal) {
  6385. if (firstNormal === void 0) { firstNormal = null; }
  6386. for (var p = 0; p < path.length; p++) {
  6387. this._curve[p].x = path[p].x;
  6388. this._curve[p].y = path[p].y;
  6389. this._curve[p].z = path[p].z;
  6390. }
  6391. this._compute(firstNormal);
  6392. return this;
  6393. };
  6394. // private function compute() : computes tangents, normals and binormals
  6395. Path3D.prototype._compute = function (firstNormal) {
  6396. var l = this._curve.length;
  6397. // first and last tangents
  6398. this._tangents[0] = this._getFirstNonNullVector(0);
  6399. if (!this._raw) {
  6400. this._tangents[0].normalize();
  6401. }
  6402. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6403. if (!this._raw) {
  6404. this._tangents[l - 1].normalize();
  6405. }
  6406. // normals and binormals at first point : arbitrary vector with _normalVector()
  6407. var tg0 = this._tangents[0];
  6408. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6409. this._normals[0] = pp0;
  6410. if (!this._raw) {
  6411. this._normals[0].normalize();
  6412. }
  6413. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6414. if (!this._raw) {
  6415. this._binormals[0].normalize();
  6416. }
  6417. this._distances[0] = 0.0;
  6418. // normals and binormals : next points
  6419. var prev; // previous vector (segment)
  6420. var cur; // current vector (segment)
  6421. var curTang; // current tangent
  6422. // previous normal
  6423. var prevBinor; // previous binormal
  6424. for (var i = 1; i < l; i++) {
  6425. // tangents
  6426. prev = this._getLastNonNullVector(i);
  6427. if (i < l - 1) {
  6428. cur = this._getFirstNonNullVector(i);
  6429. this._tangents[i] = prev.add(cur);
  6430. this._tangents[i].normalize();
  6431. }
  6432. this._distances[i] = this._distances[i - 1] + prev.length();
  6433. // normals and binormals
  6434. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6435. curTang = this._tangents[i];
  6436. prevBinor = this._binormals[i - 1];
  6437. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6438. if (!this._raw) {
  6439. this._normals[i].normalize();
  6440. }
  6441. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6442. if (!this._raw) {
  6443. this._binormals[i].normalize();
  6444. }
  6445. }
  6446. };
  6447. // private function getFirstNonNullVector(index)
  6448. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6449. Path3D.prototype._getFirstNonNullVector = function (index) {
  6450. var i = 1;
  6451. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6452. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6453. i++;
  6454. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6455. }
  6456. return nNVector;
  6457. };
  6458. // private function getLastNonNullVector(index)
  6459. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6460. Path3D.prototype._getLastNonNullVector = function (index) {
  6461. var i = 1;
  6462. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6463. while (nLVector.length() === 0 && index > i + 1) {
  6464. i++;
  6465. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6466. }
  6467. return nLVector;
  6468. };
  6469. // private function normalVector(v0, vt, va) :
  6470. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6471. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6472. Path3D.prototype._normalVector = function (v0, vt, va) {
  6473. var normal0;
  6474. var tgl = vt.length();
  6475. if (tgl === 0.0) {
  6476. tgl = 1.0;
  6477. }
  6478. if (va === undefined || va === null) {
  6479. var point;
  6480. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6481. point = new Vector3(0.0, -1.0, 0.0);
  6482. }
  6483. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6484. point = new Vector3(1.0, 0.0, 0.0);
  6485. }
  6486. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6487. point = new Vector3(0.0, 0.0, 1.0);
  6488. }
  6489. else {
  6490. point = Vector3.Zero();
  6491. }
  6492. normal0 = Vector3.Cross(vt, point);
  6493. }
  6494. else {
  6495. normal0 = Vector3.Cross(vt, va);
  6496. Vector3.CrossToRef(normal0, vt, normal0);
  6497. }
  6498. normal0.normalize();
  6499. return normal0;
  6500. };
  6501. return Path3D;
  6502. }());
  6503. BABYLON.Path3D = Path3D;
  6504. var Curve3 = /** @class */ (function () {
  6505. /**
  6506. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6507. * A Curve3 is designed from a series of successive Vector3.
  6508. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6509. */
  6510. function Curve3(points) {
  6511. this._length = 0.0;
  6512. this._points = points;
  6513. this._length = this._computeLength(points);
  6514. }
  6515. /**
  6516. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6517. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6518. * @param v1 (Vector3) the control point
  6519. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6520. * @param nbPoints (integer) the wanted number of points in the curve
  6521. */
  6522. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6523. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6524. var bez = new Array();
  6525. var equation = function (t, val0, val1, val2) {
  6526. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6527. return res;
  6528. };
  6529. for (var i = 0; i <= nbPoints; i++) {
  6530. 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)));
  6531. }
  6532. return new Curve3(bez);
  6533. };
  6534. /**
  6535. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6536. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6537. * @param v1 (Vector3) the first control point
  6538. * @param v2 (Vector3) the second control point
  6539. * @param v3 (Vector3) the end point of the Cubic Bezier
  6540. * @param nbPoints (integer) the wanted number of points in the curve
  6541. */
  6542. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6543. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6544. var bez = new Array();
  6545. var equation = function (t, val0, val1, val2, val3) {
  6546. 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;
  6547. return res;
  6548. };
  6549. for (var i = 0; i <= nbPoints; i++) {
  6550. 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)));
  6551. }
  6552. return new Curve3(bez);
  6553. };
  6554. /**
  6555. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6556. * @param p1 (Vector3) the origin point of the Hermite Spline
  6557. * @param t1 (Vector3) the tangent vector at the origin point
  6558. * @param p2 (Vector3) the end point of the Hermite Spline
  6559. * @param t2 (Vector3) the tangent vector at the end point
  6560. * @param nbPoints (integer) the wanted number of points in the curve
  6561. */
  6562. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6563. var hermite = new Array();
  6564. var step = 1.0 / nbPoints;
  6565. for (var i = 0; i <= nbPoints; i++) {
  6566. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6567. }
  6568. return new Curve3(hermite);
  6569. };
  6570. /**
  6571. * Returns a Curve3 object along a CatmullRom Spline curve :
  6572. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6573. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6574. */
  6575. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6576. var totalPoints = new Array();
  6577. totalPoints.push(points[0].clone());
  6578. Array.prototype.push.apply(totalPoints, points);
  6579. totalPoints.push(points[points.length - 1].clone());
  6580. var catmullRom = new Array();
  6581. var step = 1.0 / nbPoints;
  6582. var amount = 0.0;
  6583. for (var i = 0; i < totalPoints.length - 3; i++) {
  6584. amount = 0;
  6585. for (var c = 0; c < nbPoints; c++) {
  6586. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6587. amount += step;
  6588. }
  6589. }
  6590. i--;
  6591. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6592. return new Curve3(catmullRom);
  6593. };
  6594. /**
  6595. * Returns the Curve3 stored array of successive Vector3
  6596. */
  6597. Curve3.prototype.getPoints = function () {
  6598. return this._points;
  6599. };
  6600. /**
  6601. * Returns the computed length (float) of the curve.
  6602. */
  6603. Curve3.prototype.length = function () {
  6604. return this._length;
  6605. };
  6606. /**
  6607. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6608. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6609. * curveA and curveB keep unchanged.
  6610. */
  6611. Curve3.prototype.continue = function (curve) {
  6612. var lastPoint = this._points[this._points.length - 1];
  6613. var continuedPoints = this._points.slice();
  6614. var curvePoints = curve.getPoints();
  6615. for (var i = 1; i < curvePoints.length; i++) {
  6616. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6617. }
  6618. var continuedCurve = new Curve3(continuedPoints);
  6619. return continuedCurve;
  6620. };
  6621. Curve3.prototype._computeLength = function (path) {
  6622. var l = 0;
  6623. for (var i = 1; i < path.length; i++) {
  6624. l += (path[i].subtract(path[i - 1])).length();
  6625. }
  6626. return l;
  6627. };
  6628. return Curve3;
  6629. }());
  6630. BABYLON.Curve3 = Curve3;
  6631. // Vertex formats
  6632. var PositionNormalVertex = /** @class */ (function () {
  6633. function PositionNormalVertex(position, normal) {
  6634. if (position === void 0) { position = Vector3.Zero(); }
  6635. if (normal === void 0) { normal = Vector3.Up(); }
  6636. this.position = position;
  6637. this.normal = normal;
  6638. }
  6639. PositionNormalVertex.prototype.clone = function () {
  6640. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6641. };
  6642. return PositionNormalVertex;
  6643. }());
  6644. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6645. var PositionNormalTextureVertex = /** @class */ (function () {
  6646. function PositionNormalTextureVertex(position, normal, uv) {
  6647. if (position === void 0) { position = Vector3.Zero(); }
  6648. if (normal === void 0) { normal = Vector3.Up(); }
  6649. if (uv === void 0) { uv = Vector2.Zero(); }
  6650. this.position = position;
  6651. this.normal = normal;
  6652. this.uv = uv;
  6653. }
  6654. PositionNormalTextureVertex.prototype.clone = function () {
  6655. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6656. };
  6657. return PositionNormalTextureVertex;
  6658. }());
  6659. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6660. // Temporary pre-allocated objects for engine internal use
  6661. // usage in any internal function :
  6662. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6663. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6664. var Tmp = /** @class */ (function () {
  6665. function Tmp() {
  6666. }
  6667. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6668. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6669. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6670. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6671. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6672. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6673. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6674. Matrix.Zero(), Matrix.Zero(),
  6675. Matrix.Zero(), Matrix.Zero(),
  6676. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6677. return Tmp;
  6678. }());
  6679. BABYLON.Tmp = Tmp;
  6680. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6681. var MathTmp = /** @class */ (function () {
  6682. function MathTmp() {
  6683. }
  6684. MathTmp.Vector3 = [Vector3.Zero()];
  6685. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6686. MathTmp.Quaternion = [Quaternion.Zero()];
  6687. return MathTmp;
  6688. }());
  6689. })(BABYLON || (BABYLON = {}));
  6690. //# sourceMappingURL=babylon.math.js.map
  6691. var BABYLON;
  6692. (function (BABYLON) {
  6693. var Scalar = /** @class */ (function () {
  6694. function Scalar() {
  6695. }
  6696. /**
  6697. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6698. */
  6699. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6700. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6701. var num = a - b;
  6702. return -epsilon <= num && num <= epsilon;
  6703. };
  6704. /**
  6705. * Returns a string : the upper case translation of the number i to hexadecimal.
  6706. */
  6707. Scalar.ToHex = function (i) {
  6708. var str = i.toString(16);
  6709. if (i <= 15) {
  6710. return ("0" + str).toUpperCase();
  6711. }
  6712. return str.toUpperCase();
  6713. };
  6714. /**
  6715. * Returns -1 if value is negative and +1 is value is positive.
  6716. * Returns the value itself if it's equal to zero.
  6717. */
  6718. Scalar.Sign = function (value) {
  6719. value = +value; // convert to a number
  6720. if (value === 0 || isNaN(value))
  6721. return value;
  6722. return value > 0 ? 1 : -1;
  6723. };
  6724. /**
  6725. * Returns the value itself if it's between min and max.
  6726. * Returns min if the value is lower than min.
  6727. * Returns max if the value is greater than max.
  6728. */
  6729. Scalar.Clamp = function (value, min, max) {
  6730. if (min === void 0) { min = 0; }
  6731. if (max === void 0) { max = 1; }
  6732. return Math.min(max, Math.max(min, value));
  6733. };
  6734. /**
  6735. * Returns the log2 of value.
  6736. */
  6737. Scalar.Log2 = function (value) {
  6738. return Math.log(value) * Math.LOG2E;
  6739. };
  6740. /**
  6741. * Loops the value, so that it is never larger than length and never smaller than 0.
  6742. *
  6743. * This is similar to the modulo operator but it works with floating point numbers.
  6744. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6745. * With t = 5 and length = 2.5, the result would be 0.0.
  6746. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6747. */
  6748. Scalar.Repeat = function (value, length) {
  6749. return value - Math.floor(value / length) * length;
  6750. };
  6751. /**
  6752. * Normalize the value between 0.0 and 1.0 using min and max values
  6753. */
  6754. Scalar.Normalize = function (value, min, max) {
  6755. return (value - min) / (max - min);
  6756. };
  6757. /**
  6758. * Denormalize the value from 0.0 and 1.0 using min and max values
  6759. */
  6760. Scalar.Denormalize = function (normalized, min, max) {
  6761. return (normalized * (max - min) + min);
  6762. };
  6763. /**
  6764. * Calculates the shortest difference between two given angles given in degrees.
  6765. */
  6766. Scalar.DeltaAngle = function (current, target) {
  6767. var num = Scalar.Repeat(target - current, 360.0);
  6768. if (num > 180.0) {
  6769. num -= 360.0;
  6770. }
  6771. return num;
  6772. };
  6773. /**
  6774. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6775. *
  6776. * The returned value will move back and forth between 0 and length
  6777. */
  6778. Scalar.PingPong = function (tx, length) {
  6779. var t = Scalar.Repeat(tx, length * 2.0);
  6780. return length - Math.abs(t - length);
  6781. };
  6782. /**
  6783. * Interpolates between min and max with smoothing at the limits.
  6784. *
  6785. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6786. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6787. */
  6788. Scalar.SmoothStep = function (from, to, tx) {
  6789. var t = Scalar.Clamp(tx);
  6790. t = -2.0 * t * t * t + 3.0 * t * t;
  6791. return to * t + from * (1.0 - t);
  6792. };
  6793. /**
  6794. * Moves a value current towards target.
  6795. *
  6796. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6797. * Negative values of maxDelta pushes the value away from target.
  6798. */
  6799. Scalar.MoveTowards = function (current, target, maxDelta) {
  6800. var result = 0;
  6801. if (Math.abs(target - current) <= maxDelta) {
  6802. result = target;
  6803. }
  6804. else {
  6805. result = current + Scalar.Sign(target - current) * maxDelta;
  6806. }
  6807. return result;
  6808. };
  6809. /**
  6810. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6811. *
  6812. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6813. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6814. */
  6815. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6816. var num = Scalar.DeltaAngle(current, target);
  6817. var result = 0;
  6818. if (-maxDelta < num && num < maxDelta) {
  6819. result = target;
  6820. }
  6821. else {
  6822. target = current + num;
  6823. result = Scalar.MoveTowards(current, target, maxDelta);
  6824. }
  6825. return result;
  6826. };
  6827. /**
  6828. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6829. */
  6830. Scalar.Lerp = function (start, end, amount) {
  6831. return start + ((end - start) * amount);
  6832. };
  6833. /**
  6834. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6835. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6836. */
  6837. Scalar.LerpAngle = function (start, end, amount) {
  6838. var num = Scalar.Repeat(end - start, 360.0);
  6839. if (num > 180.0) {
  6840. num -= 360.0;
  6841. }
  6842. return start + num * Scalar.Clamp(amount);
  6843. };
  6844. /**
  6845. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6846. */
  6847. Scalar.InverseLerp = function (a, b, value) {
  6848. var result = 0;
  6849. if (a != b) {
  6850. result = Scalar.Clamp((value - a) / (b - a));
  6851. }
  6852. else {
  6853. result = 0.0;
  6854. }
  6855. return result;
  6856. };
  6857. /**
  6858. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6859. */
  6860. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6861. var squared = amount * amount;
  6862. var cubed = amount * squared;
  6863. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6864. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6865. var part3 = (cubed - (2.0 * squared)) + amount;
  6866. var part4 = cubed - squared;
  6867. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6868. };
  6869. /**
  6870. * Returns a random float number between and min and max values
  6871. */
  6872. Scalar.RandomRange = function (min, max) {
  6873. if (min === max)
  6874. return min;
  6875. return ((Math.random() * (max - min)) + min);
  6876. };
  6877. /**
  6878. * This function returns percentage of a number in a given range.
  6879. *
  6880. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6881. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6882. */
  6883. Scalar.RangeToPercent = function (number, min, max) {
  6884. return ((number - min) / (max - min));
  6885. };
  6886. /**
  6887. * This function returns number that corresponds to the percentage in a given range.
  6888. *
  6889. * PercentToRange(0.34,0,100) will return 34.
  6890. */
  6891. Scalar.PercentToRange = function (percent, min, max) {
  6892. return ((max - min) * percent + min);
  6893. };
  6894. /**
  6895. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6896. * @param angle The angle to normalize in radian.
  6897. * @return The converted angle.
  6898. */
  6899. Scalar.NormalizeRadians = function (angle) {
  6900. // More precise but slower version kept for reference.
  6901. // angle = angle % Tools.TwoPi;
  6902. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6903. //if (angle > Math.PI) {
  6904. // angle -= Tools.TwoPi;
  6905. //}
  6906. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6907. return angle;
  6908. };
  6909. /**
  6910. * Two pi constants convenient for computation.
  6911. */
  6912. Scalar.TwoPi = Math.PI * 2;
  6913. return Scalar;
  6914. }());
  6915. BABYLON.Scalar = Scalar;
  6916. })(BABYLON || (BABYLON = {}));
  6917. //# sourceMappingURL=babylon.math.scalar.js.map
  6918. //# sourceMappingURL=babylon.mixins.js.map
  6919. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6920. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6921. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6922. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6923. //# sourceMappingURL=babylon.webgl2.js.map
  6924. var BABYLON;
  6925. (function (BABYLON) {
  6926. var __decoratorInitialStore = {};
  6927. var __mergedStore = {};
  6928. var _copySource = function (creationFunction, source, instanciate) {
  6929. var destination = creationFunction();
  6930. // Tags
  6931. if (BABYLON.Tags) {
  6932. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6933. }
  6934. var classStore = getMergedStore(destination);
  6935. // Properties
  6936. for (var property in classStore) {
  6937. var propertyDescriptor = classStore[property];
  6938. var sourceProperty = source[property];
  6939. var propertyType = propertyDescriptor.type;
  6940. if (sourceProperty !== undefined && sourceProperty !== null) {
  6941. switch (propertyType) {
  6942. case 0: // Value
  6943. case 6:// Mesh reference
  6944. destination[property] = sourceProperty;
  6945. break;
  6946. case 1:// Texture
  6947. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6948. break;
  6949. case 2: // Color3
  6950. case 3: // FresnelParameters
  6951. case 4: // Vector2
  6952. case 5: // Vector3
  6953. case 7: // Color Curves
  6954. case 10:// Quaternion
  6955. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6956. break;
  6957. }
  6958. }
  6959. }
  6960. return destination;
  6961. };
  6962. function getDirectStore(target) {
  6963. var classKey = target.getClassName();
  6964. if (!__decoratorInitialStore[classKey]) {
  6965. __decoratorInitialStore[classKey] = {};
  6966. }
  6967. return __decoratorInitialStore[classKey];
  6968. }
  6969. /**
  6970. * Return the list of properties flagged as serializable
  6971. * @param target: host object
  6972. */
  6973. function getMergedStore(target) {
  6974. var classKey = target.getClassName();
  6975. if (__mergedStore[classKey]) {
  6976. return __mergedStore[classKey];
  6977. }
  6978. __mergedStore[classKey] = {};
  6979. var store = __mergedStore[classKey];
  6980. var currentTarget = target;
  6981. var currentKey = classKey;
  6982. while (currentKey) {
  6983. var initialStore = __decoratorInitialStore[currentKey];
  6984. for (var property in initialStore) {
  6985. store[property] = initialStore[property];
  6986. }
  6987. var parent_1 = void 0;
  6988. var done = false;
  6989. do {
  6990. parent_1 = Object.getPrototypeOf(currentTarget);
  6991. if (!parent_1.getClassName) {
  6992. done = true;
  6993. break;
  6994. }
  6995. if (parent_1.getClassName() !== currentKey) {
  6996. break;
  6997. }
  6998. currentTarget = parent_1;
  6999. } while (parent_1);
  7000. if (done) {
  7001. break;
  7002. }
  7003. currentKey = parent_1.getClassName();
  7004. currentTarget = parent_1;
  7005. }
  7006. return store;
  7007. }
  7008. function generateSerializableMember(type, sourceName) {
  7009. return function (target, propertyKey) {
  7010. var classStore = getDirectStore(target);
  7011. if (!classStore[propertyKey]) {
  7012. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7013. }
  7014. };
  7015. }
  7016. function generateExpandMember(setCallback, targetKey) {
  7017. if (targetKey === void 0) { targetKey = null; }
  7018. return function (target, propertyKey) {
  7019. var key = targetKey || ("_" + propertyKey);
  7020. Object.defineProperty(target, propertyKey, {
  7021. get: function () {
  7022. return this[key];
  7023. },
  7024. set: function (value) {
  7025. if (this[key] === value) {
  7026. return;
  7027. }
  7028. this[key] = value;
  7029. target[setCallback].apply(this);
  7030. },
  7031. enumerable: true,
  7032. configurable: true
  7033. });
  7034. };
  7035. }
  7036. function expandToProperty(callback, targetKey) {
  7037. if (targetKey === void 0) { targetKey = null; }
  7038. return generateExpandMember(callback, targetKey);
  7039. }
  7040. BABYLON.expandToProperty = expandToProperty;
  7041. function serialize(sourceName) {
  7042. return generateSerializableMember(0, sourceName); // value member
  7043. }
  7044. BABYLON.serialize = serialize;
  7045. function serializeAsTexture(sourceName) {
  7046. return generateSerializableMember(1, sourceName); // texture member
  7047. }
  7048. BABYLON.serializeAsTexture = serializeAsTexture;
  7049. function serializeAsColor3(sourceName) {
  7050. return generateSerializableMember(2, sourceName); // color3 member
  7051. }
  7052. BABYLON.serializeAsColor3 = serializeAsColor3;
  7053. function serializeAsFresnelParameters(sourceName) {
  7054. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7055. }
  7056. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7057. function serializeAsVector2(sourceName) {
  7058. return generateSerializableMember(4, sourceName); // vector2 member
  7059. }
  7060. BABYLON.serializeAsVector2 = serializeAsVector2;
  7061. function serializeAsVector3(sourceName) {
  7062. return generateSerializableMember(5, sourceName); // vector3 member
  7063. }
  7064. BABYLON.serializeAsVector3 = serializeAsVector3;
  7065. function serializeAsMeshReference(sourceName) {
  7066. return generateSerializableMember(6, sourceName); // mesh reference member
  7067. }
  7068. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7069. function serializeAsColorCurves(sourceName) {
  7070. return generateSerializableMember(7, sourceName); // color curves
  7071. }
  7072. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7073. function serializeAsColor4(sourceName) {
  7074. return generateSerializableMember(8, sourceName); // color 4
  7075. }
  7076. BABYLON.serializeAsColor4 = serializeAsColor4;
  7077. function serializeAsImageProcessingConfiguration(sourceName) {
  7078. return generateSerializableMember(9, sourceName); // image processing
  7079. }
  7080. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7081. function serializeAsQuaternion(sourceName) {
  7082. return generateSerializableMember(10, sourceName); // quaternion member
  7083. }
  7084. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7085. var SerializationHelper = /** @class */ (function () {
  7086. function SerializationHelper() {
  7087. }
  7088. SerializationHelper.Serialize = function (entity, serializationObject) {
  7089. if (!serializationObject) {
  7090. serializationObject = {};
  7091. }
  7092. // Tags
  7093. if (BABYLON.Tags) {
  7094. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7095. }
  7096. var serializedProperties = getMergedStore(entity);
  7097. // Properties
  7098. for (var property in serializedProperties) {
  7099. var propertyDescriptor = serializedProperties[property];
  7100. var targetPropertyName = propertyDescriptor.sourceName || property;
  7101. var propertyType = propertyDescriptor.type;
  7102. var sourceProperty = entity[property];
  7103. if (sourceProperty !== undefined && sourceProperty !== null) {
  7104. switch (propertyType) {
  7105. case 0:// Value
  7106. serializationObject[targetPropertyName] = sourceProperty;
  7107. break;
  7108. case 1:// Texture
  7109. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7110. break;
  7111. case 2:// Color3
  7112. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7113. break;
  7114. case 3:// FresnelParameters
  7115. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7116. break;
  7117. case 4:// Vector2
  7118. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7119. break;
  7120. case 5:// Vector3
  7121. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7122. break;
  7123. case 6:// Mesh reference
  7124. serializationObject[targetPropertyName] = sourceProperty.id;
  7125. break;
  7126. case 7:// Color Curves
  7127. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7128. break;
  7129. case 8:// Color 4
  7130. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7131. break;
  7132. case 9:// Image Processing
  7133. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7134. break;
  7135. }
  7136. }
  7137. }
  7138. return serializationObject;
  7139. };
  7140. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7141. if (rootUrl === void 0) { rootUrl = null; }
  7142. var destination = creationFunction();
  7143. if (!rootUrl) {
  7144. rootUrl = "";
  7145. }
  7146. // Tags
  7147. if (BABYLON.Tags) {
  7148. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7149. }
  7150. var classStore = getMergedStore(destination);
  7151. // Properties
  7152. for (var property in classStore) {
  7153. var propertyDescriptor = classStore[property];
  7154. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7155. var propertyType = propertyDescriptor.type;
  7156. if (sourceProperty !== undefined && sourceProperty !== null) {
  7157. var dest = destination;
  7158. switch (propertyType) {
  7159. case 0:// Value
  7160. dest[property] = sourceProperty;
  7161. break;
  7162. case 1:// Texture
  7163. if (scene) {
  7164. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7165. }
  7166. break;
  7167. case 2:// Color3
  7168. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7169. break;
  7170. case 3:// FresnelParameters
  7171. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7172. break;
  7173. case 4:// Vector2
  7174. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7175. break;
  7176. case 5:// Vector3
  7177. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7178. break;
  7179. case 6:// Mesh reference
  7180. if (scene) {
  7181. dest[property] = scene.getLastMeshByID(sourceProperty);
  7182. }
  7183. break;
  7184. case 7:// Color Curves
  7185. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7186. break;
  7187. case 8:// Color 4
  7188. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7189. break;
  7190. case 9:// Image Processing
  7191. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7192. break;
  7193. }
  7194. }
  7195. }
  7196. return destination;
  7197. };
  7198. SerializationHelper.Clone = function (creationFunction, source) {
  7199. return _copySource(creationFunction, source, false);
  7200. };
  7201. SerializationHelper.Instanciate = function (creationFunction, source) {
  7202. return _copySource(creationFunction, source, true);
  7203. };
  7204. return SerializationHelper;
  7205. }());
  7206. BABYLON.SerializationHelper = SerializationHelper;
  7207. })(BABYLON || (BABYLON = {}));
  7208. //# sourceMappingURL=babylon.decorators.js.map
  7209. var BABYLON;
  7210. (function (BABYLON) {
  7211. /**
  7212. * Wrapper class for promise with external resolve and reject.
  7213. */
  7214. var Deferred = /** @class */ (function () {
  7215. /**
  7216. * Constructor for this deferred object.
  7217. */
  7218. function Deferred() {
  7219. var _this = this;
  7220. this.promise = new Promise(function (resolve, reject) {
  7221. _this._resolve = resolve;
  7222. _this._reject = reject;
  7223. });
  7224. }
  7225. Object.defineProperty(Deferred.prototype, "resolve", {
  7226. /**
  7227. * The resolve method of the promise associated with this deferred object.
  7228. */
  7229. get: function () {
  7230. return this._resolve;
  7231. },
  7232. enumerable: true,
  7233. configurable: true
  7234. });
  7235. Object.defineProperty(Deferred.prototype, "reject", {
  7236. /**
  7237. * The reject method of the promise associated with this deferred object.
  7238. */
  7239. get: function () {
  7240. return this._reject;
  7241. },
  7242. enumerable: true,
  7243. configurable: true
  7244. });
  7245. return Deferred;
  7246. }());
  7247. BABYLON.Deferred = Deferred;
  7248. })(BABYLON || (BABYLON = {}));
  7249. //# sourceMappingURL=babylon.deferred.js.map
  7250. var BABYLON;
  7251. (function (BABYLON) {
  7252. /**
  7253. * A class serves as a medium between the observable and its observers
  7254. */
  7255. var EventState = /** @class */ (function () {
  7256. /**
  7257. * Create a new EventState
  7258. * @param mask defines the mask associated with this state
  7259. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7260. * @param target defines the original target of the state
  7261. * @param currentTarget defines the current target of the state
  7262. */
  7263. function EventState(mask, skipNextObservers, target, currentTarget) {
  7264. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7265. this.initalize(mask, skipNextObservers, target, currentTarget);
  7266. }
  7267. /**
  7268. * Initialize the current event state
  7269. * @param mask defines the mask associated with this state
  7270. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7271. * @param target defines the original target of the state
  7272. * @param currentTarget defines the current target of the state
  7273. * @returns the current event state
  7274. */
  7275. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7276. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7277. this.mask = mask;
  7278. this.skipNextObservers = skipNextObservers;
  7279. this.target = target;
  7280. this.currentTarget = currentTarget;
  7281. return this;
  7282. };
  7283. return EventState;
  7284. }());
  7285. BABYLON.EventState = EventState;
  7286. /**
  7287. * Represent an Observer registered to a given Observable object.
  7288. */
  7289. var Observer = /** @class */ (function () {
  7290. /**
  7291. * Creates a new observer
  7292. * @param callback defines the callback to call when the observer is notified
  7293. * @param mask defines the mask of the observer (used to filter notifications)
  7294. * @param scope defines the current scope used to restore the JS context
  7295. */
  7296. function Observer(
  7297. /**
  7298. * Defines the callback to call when the observer is notified
  7299. */
  7300. callback,
  7301. /**
  7302. * Defines the mask of the observer (used to filter notifications)
  7303. */
  7304. mask,
  7305. /**
  7306. * Defines the current scope used to restore the JS context
  7307. */
  7308. scope) {
  7309. if (scope === void 0) { scope = null; }
  7310. this.callback = callback;
  7311. this.mask = mask;
  7312. this.scope = scope;
  7313. /** @ignore */
  7314. this._willBeUnregistered = false;
  7315. /**
  7316. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7317. */
  7318. this.unregisterOnNextCall = false;
  7319. }
  7320. return Observer;
  7321. }());
  7322. BABYLON.Observer = Observer;
  7323. /**
  7324. * Represent a list of observers registered to multiple Observables object.
  7325. */
  7326. var MultiObserver = /** @class */ (function () {
  7327. function MultiObserver() {
  7328. }
  7329. /**
  7330. * Release associated resources
  7331. */
  7332. MultiObserver.prototype.dispose = function () {
  7333. if (this._observers && this._observables) {
  7334. for (var index = 0; index < this._observers.length; index++) {
  7335. this._observables[index].remove(this._observers[index]);
  7336. }
  7337. }
  7338. this._observers = null;
  7339. this._observables = null;
  7340. };
  7341. /**
  7342. * Raise a callback when one of the observable will notify
  7343. * @param observables defines a list of observables to watch
  7344. * @param callback defines the callback to call on notification
  7345. * @param mask defines the mask used to filter notifications
  7346. * @param scope defines the current scope used to restore the JS context
  7347. * @returns the new MultiObserver
  7348. */
  7349. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7350. if (mask === void 0) { mask = -1; }
  7351. if (scope === void 0) { scope = null; }
  7352. var result = new MultiObserver();
  7353. result._observers = new Array();
  7354. result._observables = observables;
  7355. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7356. var observable = observables_1[_i];
  7357. var observer = observable.add(callback, mask, false, scope);
  7358. if (observer) {
  7359. result._observers.push(observer);
  7360. }
  7361. }
  7362. return result;
  7363. };
  7364. return MultiObserver;
  7365. }());
  7366. BABYLON.MultiObserver = MultiObserver;
  7367. /**
  7368. * The Observable class is a simple implementation of the Observable pattern.
  7369. * 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.
  7370. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7371. * 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).
  7372. * 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.
  7373. */
  7374. var Observable = /** @class */ (function () {
  7375. /**
  7376. * Creates a new observable
  7377. * @param onObserverAdded defines a callback to call when a new observer is added
  7378. */
  7379. function Observable(onObserverAdded) {
  7380. this._observers = new Array();
  7381. this._eventState = new EventState(0);
  7382. if (onObserverAdded) {
  7383. this._onObserverAdded = onObserverAdded;
  7384. }
  7385. }
  7386. /**
  7387. * Create a new Observer with the specified callback
  7388. * @param callback the callback that will be executed for that Observer
  7389. * @param mask the mask used to filter observers
  7390. * @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.
  7391. * @param scope optional scope for the callback to be called from
  7392. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7393. * @returns the new observer created for the callback
  7394. */
  7395. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7396. if (mask === void 0) { mask = -1; }
  7397. if (insertFirst === void 0) { insertFirst = false; }
  7398. if (scope === void 0) { scope = null; }
  7399. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7400. if (!callback) {
  7401. return null;
  7402. }
  7403. var observer = new Observer(callback, mask, scope);
  7404. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7405. if (insertFirst) {
  7406. this._observers.unshift(observer);
  7407. }
  7408. else {
  7409. this._observers.push(observer);
  7410. }
  7411. if (this._onObserverAdded) {
  7412. this._onObserverAdded(observer);
  7413. }
  7414. return observer;
  7415. };
  7416. /**
  7417. * Remove an Observer from the Observable object
  7418. * @param observer the instance of the Observer to remove
  7419. * @returns false if it doesn't belong to this Observable
  7420. */
  7421. Observable.prototype.remove = function (observer) {
  7422. if (!observer) {
  7423. return false;
  7424. }
  7425. var index = this._observers.indexOf(observer);
  7426. if (index !== -1) {
  7427. this._observers.splice(index, 1);
  7428. return true;
  7429. }
  7430. return false;
  7431. };
  7432. /**
  7433. * Remove a callback from the Observable object
  7434. * @param callback the callback to remove
  7435. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7436. * @returns false if it doesn't belong to this Observable
  7437. */
  7438. Observable.prototype.removeCallback = function (callback, scope) {
  7439. for (var index = 0; index < this._observers.length; index++) {
  7440. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7441. this._observers.splice(index, 1);
  7442. return true;
  7443. }
  7444. }
  7445. return false;
  7446. };
  7447. Observable.prototype._deferUnregister = function (observer) {
  7448. var _this = this;
  7449. observer.unregisterOnNextCall = false;
  7450. observer._willBeUnregistered = true;
  7451. BABYLON.Tools.SetImmediate(function () {
  7452. _this.remove(observer);
  7453. });
  7454. };
  7455. /**
  7456. * Notify all Observers by calling their respective callback with the given data
  7457. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7458. * @param eventData defines the data to send to all observers
  7459. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7460. * @param target defines the original target of the state
  7461. * @param currentTarget defines the current target of the state
  7462. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7463. */
  7464. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7465. if (mask === void 0) { mask = -1; }
  7466. if (!this._observers.length) {
  7467. return true;
  7468. }
  7469. var state = this._eventState;
  7470. state.mask = mask;
  7471. state.target = target;
  7472. state.currentTarget = currentTarget;
  7473. state.skipNextObservers = false;
  7474. state.lastReturnValue = eventData;
  7475. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7476. var obs = _a[_i];
  7477. if (obs._willBeUnregistered) {
  7478. continue;
  7479. }
  7480. if (obs.mask & mask) {
  7481. if (obs.scope) {
  7482. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7483. }
  7484. else {
  7485. state.lastReturnValue = obs.callback(eventData, state);
  7486. }
  7487. if (obs.unregisterOnNextCall) {
  7488. this._deferUnregister(obs);
  7489. }
  7490. }
  7491. if (state.skipNextObservers) {
  7492. return false;
  7493. }
  7494. }
  7495. return true;
  7496. };
  7497. /**
  7498. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7499. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7500. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7501. * and it is crucial that all callbacks will be executed.
  7502. * The order of the callbacks is kept, callbacks are not executed parallel.
  7503. *
  7504. * @param eventData The data to be sent to each callback
  7505. * @param mask is used to filter observers defaults to -1
  7506. * @param target defines the callback target (see EventState)
  7507. * @param currentTarget defines he current object in the bubbling phase
  7508. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7509. */
  7510. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7511. var _this = this;
  7512. if (mask === void 0) { mask = -1; }
  7513. // create an empty promise
  7514. var p = Promise.resolve(eventData);
  7515. // no observers? return this promise.
  7516. if (!this._observers.length) {
  7517. return p;
  7518. }
  7519. var state = this._eventState;
  7520. state.mask = mask;
  7521. state.target = target;
  7522. state.currentTarget = currentTarget;
  7523. state.skipNextObservers = false;
  7524. // execute one callback after another (not using Promise.all, the order is important)
  7525. this._observers.forEach(function (obs) {
  7526. if (state.skipNextObservers) {
  7527. return;
  7528. }
  7529. if (obs._willBeUnregistered) {
  7530. return;
  7531. }
  7532. if (obs.mask & mask) {
  7533. if (obs.scope) {
  7534. p = p.then(function (lastReturnedValue) {
  7535. state.lastReturnValue = lastReturnedValue;
  7536. return obs.callback.apply(obs.scope, [eventData, state]);
  7537. });
  7538. }
  7539. else {
  7540. p = p.then(function (lastReturnedValue) {
  7541. state.lastReturnValue = lastReturnedValue;
  7542. return obs.callback(eventData, state);
  7543. });
  7544. }
  7545. if (obs.unregisterOnNextCall) {
  7546. _this._deferUnregister(obs);
  7547. }
  7548. }
  7549. });
  7550. // return the eventData
  7551. return p.then(function () { return eventData; });
  7552. };
  7553. /**
  7554. * Notify a specific observer
  7555. * @param observer defines the observer to notify
  7556. * @param eventData defines the data to be sent to each callback
  7557. * @param mask is used to filter observers defaults to -1
  7558. */
  7559. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7560. if (mask === void 0) { mask = -1; }
  7561. var state = this._eventState;
  7562. state.mask = mask;
  7563. state.skipNextObservers = false;
  7564. observer.callback(eventData, state);
  7565. };
  7566. /**
  7567. * Gets a boolean indicating if the observable has at least one observer
  7568. * @returns true is the Observable has at least one Observer registered
  7569. */
  7570. Observable.prototype.hasObservers = function () {
  7571. return this._observers.length > 0;
  7572. };
  7573. /**
  7574. * Clear the list of observers
  7575. */
  7576. Observable.prototype.clear = function () {
  7577. this._observers = new Array();
  7578. this._onObserverAdded = null;
  7579. };
  7580. /**
  7581. * Clone the current observable
  7582. * @returns a new observable
  7583. */
  7584. Observable.prototype.clone = function () {
  7585. var result = new Observable();
  7586. result._observers = this._observers.slice(0);
  7587. return result;
  7588. };
  7589. /**
  7590. * Does this observable handles observer registered with a given mask
  7591. * @param mask defines the mask to be tested
  7592. * @return whether or not one observer registered with the given mask is handeled
  7593. **/
  7594. Observable.prototype.hasSpecificMask = function (mask) {
  7595. if (mask === void 0) { mask = -1; }
  7596. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7597. var obs = _a[_i];
  7598. if (obs.mask & mask || obs.mask === mask) {
  7599. return true;
  7600. }
  7601. }
  7602. return false;
  7603. };
  7604. return Observable;
  7605. }());
  7606. BABYLON.Observable = Observable;
  7607. })(BABYLON || (BABYLON = {}));
  7608. //# sourceMappingURL=babylon.observable.js.map
  7609. var BABYLON;
  7610. (function (BABYLON) {
  7611. var SmartArray = /** @class */ (function () {
  7612. function SmartArray(capacity) {
  7613. this.length = 0;
  7614. this.data = new Array(capacity);
  7615. this._id = SmartArray._GlobalId++;
  7616. }
  7617. SmartArray.prototype.push = function (value) {
  7618. this.data[this.length++] = value;
  7619. if (this.length > this.data.length) {
  7620. this.data.length *= 2;
  7621. }
  7622. };
  7623. SmartArray.prototype.forEach = function (func) {
  7624. for (var index = 0; index < this.length; index++) {
  7625. func(this.data[index]);
  7626. }
  7627. };
  7628. SmartArray.prototype.sort = function (compareFn) {
  7629. this.data.sort(compareFn);
  7630. };
  7631. SmartArray.prototype.reset = function () {
  7632. this.length = 0;
  7633. };
  7634. SmartArray.prototype.dispose = function () {
  7635. this.reset();
  7636. if (this.data) {
  7637. this.data.length = 0;
  7638. this.data = [];
  7639. }
  7640. };
  7641. SmartArray.prototype.concat = function (array) {
  7642. if (array.length === 0) {
  7643. return;
  7644. }
  7645. if (this.length + array.length > this.data.length) {
  7646. this.data.length = (this.length + array.length) * 2;
  7647. }
  7648. for (var index = 0; index < array.length; index++) {
  7649. this.data[this.length++] = (array.data || array)[index];
  7650. }
  7651. };
  7652. SmartArray.prototype.indexOf = function (value) {
  7653. var position = this.data.indexOf(value);
  7654. if (position >= this.length) {
  7655. return -1;
  7656. }
  7657. return position;
  7658. };
  7659. SmartArray.prototype.contains = function (value) {
  7660. return this.data.indexOf(value) !== -1;
  7661. };
  7662. // Statics
  7663. SmartArray._GlobalId = 0;
  7664. return SmartArray;
  7665. }());
  7666. BABYLON.SmartArray = SmartArray;
  7667. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7668. __extends(SmartArrayNoDuplicate, _super);
  7669. function SmartArrayNoDuplicate() {
  7670. var _this = _super !== null && _super.apply(this, arguments) || this;
  7671. _this._duplicateId = 0;
  7672. return _this;
  7673. }
  7674. SmartArrayNoDuplicate.prototype.push = function (value) {
  7675. _super.prototype.push.call(this, value);
  7676. if (!value.__smartArrayFlags) {
  7677. value.__smartArrayFlags = {};
  7678. }
  7679. value.__smartArrayFlags[this._id] = this._duplicateId;
  7680. };
  7681. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7682. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7683. return false;
  7684. }
  7685. this.push(value);
  7686. return true;
  7687. };
  7688. SmartArrayNoDuplicate.prototype.reset = function () {
  7689. _super.prototype.reset.call(this);
  7690. this._duplicateId++;
  7691. };
  7692. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7693. if (array.length === 0) {
  7694. return;
  7695. }
  7696. if (this.length + array.length > this.data.length) {
  7697. this.data.length = (this.length + array.length) * 2;
  7698. }
  7699. for (var index = 0; index < array.length; index++) {
  7700. var item = (array.data || array)[index];
  7701. this.pushNoDuplicate(item);
  7702. }
  7703. };
  7704. return SmartArrayNoDuplicate;
  7705. }(SmartArray));
  7706. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7707. })(BABYLON || (BABYLON = {}));
  7708. //# sourceMappingURL=babylon.smartArray.js.map
  7709. var BABYLON;
  7710. (function (BABYLON) {
  7711. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7712. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7713. var LoadFileError = /** @class */ (function (_super) {
  7714. __extends(LoadFileError, _super);
  7715. function LoadFileError(message, request) {
  7716. var _this = _super.call(this, message) || this;
  7717. _this.request = request;
  7718. _this.name = "LoadFileError";
  7719. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7720. return _this;
  7721. }
  7722. // Polyfill for Object.setPrototypeOf if necessary.
  7723. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7724. return LoadFileError;
  7725. }(Error));
  7726. BABYLON.LoadFileError = LoadFileError;
  7727. var RetryStrategy = /** @class */ (function () {
  7728. function RetryStrategy() {
  7729. }
  7730. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7731. if (maxRetries === void 0) { maxRetries = 3; }
  7732. if (baseInterval === void 0) { baseInterval = 500; }
  7733. return function (url, request, retryIndex) {
  7734. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7735. return -1;
  7736. }
  7737. return Math.pow(2, retryIndex) * baseInterval;
  7738. };
  7739. };
  7740. return RetryStrategy;
  7741. }());
  7742. BABYLON.RetryStrategy = RetryStrategy;
  7743. // Screenshots
  7744. var screenshotCanvas;
  7745. var cloneValue = function (source, destinationObject) {
  7746. if (!source)
  7747. return null;
  7748. if (source instanceof BABYLON.Mesh) {
  7749. return null;
  7750. }
  7751. if (source instanceof BABYLON.SubMesh) {
  7752. return source.clone(destinationObject);
  7753. }
  7754. else if (source.clone) {
  7755. return source.clone();
  7756. }
  7757. return null;
  7758. };
  7759. var Tools = /** @class */ (function () {
  7760. function Tools() {
  7761. }
  7762. /**
  7763. * Interpolates between a and b via alpha
  7764. * @param a The lower value (returned when alpha = 0)
  7765. * @param b The upper value (returned when alpha = 1)
  7766. * @param alpha The interpolation-factor
  7767. * @return The mixed value
  7768. */
  7769. Tools.Mix = function (a, b, alpha) {
  7770. return a * (1 - alpha) + b * alpha;
  7771. };
  7772. Tools.Instantiate = function (className) {
  7773. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7774. return Tools.RegisteredExternalClasses[className];
  7775. }
  7776. var arr = className.split(".");
  7777. var fn = (window || this);
  7778. for (var i = 0, len = arr.length; i < len; i++) {
  7779. fn = fn[arr[i]];
  7780. }
  7781. if (typeof fn !== "function") {
  7782. return null;
  7783. }
  7784. return fn;
  7785. };
  7786. /**
  7787. * Provides a slice function that will work even on IE
  7788. * @param data defines the array to slice
  7789. * @returns the new sliced array
  7790. */
  7791. Tools.Slice = function (data) {
  7792. if (data.slice) {
  7793. return data.slice();
  7794. }
  7795. return Array.prototype.slice.call(data);
  7796. };
  7797. Tools.SetImmediate = function (action) {
  7798. if (window.setImmediate) {
  7799. window.setImmediate(action);
  7800. }
  7801. else {
  7802. setTimeout(action, 1);
  7803. }
  7804. };
  7805. Tools.IsExponentOfTwo = function (value) {
  7806. var count = 1;
  7807. do {
  7808. count *= 2;
  7809. } while (count < value);
  7810. return count === value;
  7811. };
  7812. /**
  7813. * Find the next highest power of two.
  7814. * @param x Number to start search from.
  7815. * @return Next highest power of two.
  7816. */
  7817. Tools.CeilingPOT = function (x) {
  7818. x--;
  7819. x |= x >> 1;
  7820. x |= x >> 2;
  7821. x |= x >> 4;
  7822. x |= x >> 8;
  7823. x |= x >> 16;
  7824. x++;
  7825. return x;
  7826. };
  7827. /**
  7828. * Find the next lowest power of two.
  7829. * @param x Number to start search from.
  7830. * @return Next lowest power of two.
  7831. */
  7832. Tools.FloorPOT = function (x) {
  7833. x = x | (x >> 1);
  7834. x = x | (x >> 2);
  7835. x = x | (x >> 4);
  7836. x = x | (x >> 8);
  7837. x = x | (x >> 16);
  7838. return x - (x >> 1);
  7839. };
  7840. /**
  7841. * Find the nearest power of two.
  7842. * @param x Number to start search from.
  7843. * @return Next nearest power of two.
  7844. */
  7845. Tools.NearestPOT = function (x) {
  7846. var c = Tools.CeilingPOT(x);
  7847. var f = Tools.FloorPOT(x);
  7848. return (c - x) > (x - f) ? f : c;
  7849. };
  7850. Tools.GetExponentOfTwo = function (value, max, mode) {
  7851. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7852. var pot;
  7853. switch (mode) {
  7854. case BABYLON.Engine.SCALEMODE_FLOOR:
  7855. pot = Tools.FloorPOT(value);
  7856. break;
  7857. case BABYLON.Engine.SCALEMODE_NEAREST:
  7858. pot = Tools.NearestPOT(value);
  7859. break;
  7860. case BABYLON.Engine.SCALEMODE_CEILING:
  7861. default:
  7862. pot = Tools.CeilingPOT(value);
  7863. break;
  7864. }
  7865. return Math.min(pot, max);
  7866. };
  7867. Tools.GetFilename = function (path) {
  7868. var index = path.lastIndexOf("/");
  7869. if (index < 0)
  7870. return path;
  7871. return path.substring(index + 1);
  7872. };
  7873. /**
  7874. * Extracts the "folder" part of a path (everything before the filename).
  7875. * @param uri The URI to extract the info from
  7876. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7877. * @returns The "folder" part of the path
  7878. */
  7879. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7880. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7881. var index = uri.lastIndexOf("/");
  7882. if (index < 0) {
  7883. if (returnUnchangedIfNoSlash) {
  7884. return uri;
  7885. }
  7886. return "";
  7887. }
  7888. return uri.substring(0, index + 1);
  7889. };
  7890. Tools.GetDOMTextContent = function (element) {
  7891. var result = "";
  7892. var child = element.firstChild;
  7893. while (child) {
  7894. if (child.nodeType === 3) {
  7895. result += child.textContent;
  7896. }
  7897. child = child.nextSibling;
  7898. }
  7899. return result;
  7900. };
  7901. Tools.ToDegrees = function (angle) {
  7902. return angle * 180 / Math.PI;
  7903. };
  7904. Tools.ToRadians = function (angle) {
  7905. return angle * Math.PI / 180;
  7906. };
  7907. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7908. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7909. var output = "";
  7910. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7911. var i = 0;
  7912. var bytes = new Uint8Array(buffer);
  7913. while (i < bytes.length) {
  7914. chr1 = bytes[i++];
  7915. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7916. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7917. enc1 = chr1 >> 2;
  7918. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7919. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7920. enc4 = chr3 & 63;
  7921. if (isNaN(chr2)) {
  7922. enc3 = enc4 = 64;
  7923. }
  7924. else if (isNaN(chr3)) {
  7925. enc4 = 64;
  7926. }
  7927. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7928. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7929. }
  7930. return "data:image/png;base64," + output;
  7931. };
  7932. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7933. if (bias === void 0) { bias = null; }
  7934. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7935. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7936. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7937. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7938. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7939. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7940. }
  7941. if (bias) {
  7942. minimum.x -= minimum.x * bias.x + bias.y;
  7943. minimum.y -= minimum.y * bias.x + bias.y;
  7944. minimum.z -= minimum.z * bias.x + bias.y;
  7945. maximum.x += maximum.x * bias.x + bias.y;
  7946. maximum.y += maximum.y * bias.x + bias.y;
  7947. maximum.z += maximum.z * bias.x + bias.y;
  7948. }
  7949. return {
  7950. minimum: minimum,
  7951. maximum: maximum
  7952. };
  7953. };
  7954. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7955. if (bias === void 0) { bias = null; }
  7956. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7957. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7958. if (!stride) {
  7959. stride = 3;
  7960. }
  7961. for (var index = start; index < start + count; index++) {
  7962. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7963. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7964. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7965. }
  7966. if (bias) {
  7967. minimum.x -= minimum.x * bias.x + bias.y;
  7968. minimum.y -= minimum.y * bias.x + bias.y;
  7969. minimum.z -= minimum.z * bias.x + bias.y;
  7970. maximum.x += maximum.x * bias.x + bias.y;
  7971. maximum.y += maximum.y * bias.x + bias.y;
  7972. maximum.z += maximum.z * bias.x + bias.y;
  7973. }
  7974. return {
  7975. minimum: minimum,
  7976. maximum: maximum
  7977. };
  7978. };
  7979. Tools.Vector2ArrayFeeder = function (array) {
  7980. return function (index) {
  7981. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7982. var length = isFloatArray ? array.length / 2 : array.length;
  7983. if (index >= length) {
  7984. return null;
  7985. }
  7986. if (isFloatArray) {
  7987. var fa = array;
  7988. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7989. }
  7990. var a = array;
  7991. return a[index];
  7992. };
  7993. };
  7994. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7995. if (bias === void 0) { bias = null; }
  7996. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7997. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7998. var i = 0;
  7999. var cur = feeder(i++);
  8000. while (cur) {
  8001. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8002. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8003. cur = feeder(i++);
  8004. }
  8005. if (bias) {
  8006. minimum.x -= minimum.x * bias.x + bias.y;
  8007. minimum.y -= minimum.y * bias.x + bias.y;
  8008. maximum.x += maximum.x * bias.x + bias.y;
  8009. maximum.y += maximum.y * bias.x + bias.y;
  8010. }
  8011. return {
  8012. minimum: minimum,
  8013. maximum: maximum
  8014. };
  8015. };
  8016. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8017. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8018. return null;
  8019. return Array.isArray(obj) ? obj : [obj];
  8020. };
  8021. // Misc.
  8022. Tools.GetPointerPrefix = function () {
  8023. var eventPrefix = "pointer";
  8024. // Check if pointer events are supported
  8025. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8026. eventPrefix = "mouse";
  8027. }
  8028. return eventPrefix;
  8029. };
  8030. /**
  8031. * @param func - the function to be called
  8032. * @param requester - the object that will request the next frame. Falls back to window.
  8033. */
  8034. Tools.QueueNewFrame = function (func, requester) {
  8035. if (!Tools.IsWindowObjectExist()) {
  8036. return setTimeout(func, 16);
  8037. }
  8038. if (!requester) {
  8039. requester = window;
  8040. }
  8041. if (requester.requestAnimationFrame) {
  8042. return requester.requestAnimationFrame(func);
  8043. }
  8044. else if (requester.msRequestAnimationFrame) {
  8045. return requester.msRequestAnimationFrame(func);
  8046. }
  8047. else if (requester.webkitRequestAnimationFrame) {
  8048. return requester.webkitRequestAnimationFrame(func);
  8049. }
  8050. else if (requester.mozRequestAnimationFrame) {
  8051. return requester.mozRequestAnimationFrame(func);
  8052. }
  8053. else if (requester.oRequestAnimationFrame) {
  8054. return requester.oRequestAnimationFrame(func);
  8055. }
  8056. else {
  8057. return window.setTimeout(func, 16);
  8058. }
  8059. };
  8060. Tools.RequestFullscreen = function (element) {
  8061. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8062. if (!requestFunction)
  8063. return;
  8064. requestFunction.call(element);
  8065. };
  8066. Tools.ExitFullscreen = function () {
  8067. if (document.exitFullscreen) {
  8068. document.exitFullscreen();
  8069. }
  8070. else if (document.mozCancelFullScreen) {
  8071. document.mozCancelFullScreen();
  8072. }
  8073. else if (document.webkitCancelFullScreen) {
  8074. document.webkitCancelFullScreen();
  8075. }
  8076. else if (document.msCancelFullScreen) {
  8077. document.msCancelFullScreen();
  8078. }
  8079. };
  8080. Tools.SetCorsBehavior = function (url, element) {
  8081. if (url && url.indexOf("data:") === 0) {
  8082. return;
  8083. }
  8084. if (Tools.CorsBehavior) {
  8085. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8086. element.crossOrigin = Tools.CorsBehavior;
  8087. }
  8088. else {
  8089. var result = Tools.CorsBehavior(url);
  8090. if (result) {
  8091. element.crossOrigin = result;
  8092. }
  8093. }
  8094. }
  8095. };
  8096. // External files
  8097. Tools.CleanUrl = function (url) {
  8098. url = url.replace(/#/mg, "%23");
  8099. return url;
  8100. };
  8101. Tools.LoadImage = function (url, onLoad, onError, database) {
  8102. if (url instanceof ArrayBuffer) {
  8103. url = Tools.EncodeArrayBufferTobase64(url);
  8104. }
  8105. url = Tools.CleanUrl(url);
  8106. url = Tools.PreprocessUrl(url);
  8107. var img = new Image();
  8108. Tools.SetCorsBehavior(url, img);
  8109. var loadHandler = function () {
  8110. img.removeEventListener("load", loadHandler);
  8111. img.removeEventListener("error", errorHandler);
  8112. onLoad(img);
  8113. };
  8114. var errorHandler = function (err) {
  8115. img.removeEventListener("load", loadHandler);
  8116. img.removeEventListener("error", errorHandler);
  8117. Tools.Error("Error while trying to load image: " + url);
  8118. if (onError) {
  8119. onError("Error while trying to load image: " + url, err);
  8120. }
  8121. };
  8122. img.addEventListener("load", loadHandler);
  8123. img.addEventListener("error", errorHandler);
  8124. var noIndexedDB = function () {
  8125. img.src = url;
  8126. };
  8127. var loadFromIndexedDB = function () {
  8128. if (database) {
  8129. database.loadImageFromDB(url, img);
  8130. }
  8131. };
  8132. //ANY database to do!
  8133. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8134. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8135. }
  8136. else {
  8137. if (url.indexOf("file:") !== -1) {
  8138. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8139. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8140. try {
  8141. var blobURL;
  8142. try {
  8143. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8144. }
  8145. catch (ex) {
  8146. // Chrome doesn't support oneTimeOnly parameter
  8147. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8148. }
  8149. img.src = blobURL;
  8150. }
  8151. catch (e) {
  8152. img.src = "";
  8153. }
  8154. return img;
  8155. }
  8156. }
  8157. noIndexedDB();
  8158. }
  8159. return img;
  8160. };
  8161. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8162. url = Tools.CleanUrl(url);
  8163. url = Tools.PreprocessUrl(url);
  8164. // If file and file input are set
  8165. if (url.indexOf("file:") !== -1) {
  8166. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8167. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8168. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8169. }
  8170. }
  8171. var loadUrl = Tools.BaseUrl + url;
  8172. var aborted = false;
  8173. var fileRequest = {
  8174. onCompleteObservable: new BABYLON.Observable(),
  8175. abort: function () { return aborted = true; },
  8176. };
  8177. var requestFile = function () {
  8178. var request = new XMLHttpRequest();
  8179. var retryHandle = null;
  8180. fileRequest.abort = function () {
  8181. aborted = true;
  8182. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8183. request.abort();
  8184. }
  8185. if (retryHandle !== null) {
  8186. clearTimeout(retryHandle);
  8187. retryHandle = null;
  8188. }
  8189. };
  8190. var retryLoop = function (retryIndex) {
  8191. request.open('GET', loadUrl, true);
  8192. if (useArrayBuffer) {
  8193. request.responseType = "arraybuffer";
  8194. }
  8195. if (onProgress) {
  8196. request.addEventListener("progress", onProgress);
  8197. }
  8198. var onLoadEnd = function () {
  8199. request.removeEventListener("loadend", onLoadEnd);
  8200. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8201. fileRequest.onCompleteObservable.clear();
  8202. };
  8203. request.addEventListener("loadend", onLoadEnd);
  8204. var onReadyStateChange = function () {
  8205. if (aborted) {
  8206. return;
  8207. }
  8208. // In case of undefined state in some browsers.
  8209. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8210. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8211. request.removeEventListener("readystatechange", onReadyStateChange);
  8212. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8213. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8214. return;
  8215. }
  8216. var retryStrategy = Tools.DefaultRetryStrategy;
  8217. if (retryStrategy) {
  8218. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8219. if (waitTime !== -1) {
  8220. // Prevent the request from completing for retry.
  8221. request.removeEventListener("loadend", onLoadEnd);
  8222. request = new XMLHttpRequest();
  8223. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8224. return;
  8225. }
  8226. }
  8227. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8228. if (onError) {
  8229. onError(request, e);
  8230. }
  8231. else {
  8232. throw e;
  8233. }
  8234. }
  8235. };
  8236. request.addEventListener("readystatechange", onReadyStateChange);
  8237. request.send();
  8238. };
  8239. retryLoop(0);
  8240. };
  8241. // Caching all files
  8242. if (database && database.enableSceneOffline) {
  8243. var noIndexedDB_1 = function () {
  8244. if (!aborted) {
  8245. requestFile();
  8246. }
  8247. };
  8248. var loadFromIndexedDB = function () {
  8249. // TODO: database needs to support aborting and should return a IFileRequest
  8250. if (aborted) {
  8251. return;
  8252. }
  8253. if (database) {
  8254. database.loadFileFromDB(url, function (data) {
  8255. if (!aborted) {
  8256. onSuccess(data);
  8257. }
  8258. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8259. }, onProgress ? function (event) {
  8260. if (!aborted) {
  8261. onProgress(event);
  8262. }
  8263. } : undefined, noIndexedDB_1, useArrayBuffer);
  8264. }
  8265. };
  8266. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8267. }
  8268. else {
  8269. requestFile();
  8270. }
  8271. return fileRequest;
  8272. };
  8273. /**
  8274. * Load a script (identified by an url). When the url returns, the
  8275. * content of this file is added into a new script element, attached to the DOM (body element)
  8276. */
  8277. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8278. var head = document.getElementsByTagName('head')[0];
  8279. var script = document.createElement('script');
  8280. script.type = 'text/javascript';
  8281. script.src = scriptUrl;
  8282. script.onload = function () {
  8283. if (onSuccess) {
  8284. onSuccess();
  8285. }
  8286. };
  8287. script.onerror = function (e) {
  8288. if (onError) {
  8289. onError("Unable to load script", e);
  8290. }
  8291. };
  8292. head.appendChild(script);
  8293. };
  8294. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8295. var reader = new FileReader();
  8296. var request = {
  8297. onCompleteObservable: new BABYLON.Observable(),
  8298. abort: function () { return reader.abort(); },
  8299. };
  8300. reader.onloadend = function (e) {
  8301. request.onCompleteObservable.notifyObservers(request);
  8302. };
  8303. reader.onload = function (e) {
  8304. //target doesn't have result from ts 1.3
  8305. callback(e.target['result']);
  8306. };
  8307. reader.onprogress = progressCallback;
  8308. reader.readAsDataURL(fileToLoad);
  8309. return request;
  8310. };
  8311. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8312. var reader = new FileReader();
  8313. var request = {
  8314. onCompleteObservable: new BABYLON.Observable(),
  8315. abort: function () { return reader.abort(); },
  8316. };
  8317. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8318. reader.onerror = function (e) {
  8319. Tools.Log("Error while reading file: " + fileToLoad.name);
  8320. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8321. };
  8322. reader.onload = function (e) {
  8323. //target doesn't have result from ts 1.3
  8324. callback(e.target['result']);
  8325. };
  8326. if (progressCallBack) {
  8327. reader.onprogress = progressCallBack;
  8328. }
  8329. if (!useArrayBuffer) {
  8330. // Asynchronous read
  8331. reader.readAsText(fileToLoad);
  8332. }
  8333. else {
  8334. reader.readAsArrayBuffer(fileToLoad);
  8335. }
  8336. return request;
  8337. };
  8338. //returns a downloadable url to a file content.
  8339. Tools.FileAsURL = function (content) {
  8340. var fileBlob = new Blob([content]);
  8341. var url = window.URL || window.webkitURL;
  8342. var link = url.createObjectURL(fileBlob);
  8343. return link;
  8344. };
  8345. // Misc.
  8346. Tools.Format = function (value, decimals) {
  8347. if (decimals === void 0) { decimals = 2; }
  8348. return value.toFixed(decimals);
  8349. };
  8350. Tools.CheckExtends = function (v, min, max) {
  8351. if (v.x < min.x)
  8352. min.x = v.x;
  8353. if (v.y < min.y)
  8354. min.y = v.y;
  8355. if (v.z < min.z)
  8356. min.z = v.z;
  8357. if (v.x > max.x)
  8358. max.x = v.x;
  8359. if (v.y > max.y)
  8360. max.y = v.y;
  8361. if (v.z > max.z)
  8362. max.z = v.z;
  8363. };
  8364. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8365. for (var prop in source) {
  8366. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8367. continue;
  8368. }
  8369. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8370. continue;
  8371. }
  8372. var sourceValue = source[prop];
  8373. var typeOfSourceValue = typeof sourceValue;
  8374. if (typeOfSourceValue === "function") {
  8375. continue;
  8376. }
  8377. if (typeOfSourceValue === "object") {
  8378. if (sourceValue instanceof Array) {
  8379. destination[prop] = [];
  8380. if (sourceValue.length > 0) {
  8381. if (typeof sourceValue[0] == "object") {
  8382. for (var index = 0; index < sourceValue.length; index++) {
  8383. var clonedValue = cloneValue(sourceValue[index], destination);
  8384. if (destination[prop].indexOf(clonedValue) === -1) {
  8385. destination[prop].push(clonedValue);
  8386. }
  8387. }
  8388. }
  8389. else {
  8390. destination[prop] = sourceValue.slice(0);
  8391. }
  8392. }
  8393. }
  8394. else {
  8395. destination[prop] = cloneValue(sourceValue, destination);
  8396. }
  8397. }
  8398. else {
  8399. destination[prop] = sourceValue;
  8400. }
  8401. }
  8402. };
  8403. Tools.IsEmpty = function (obj) {
  8404. for (var i in obj) {
  8405. if (obj.hasOwnProperty(i)) {
  8406. return false;
  8407. }
  8408. }
  8409. return true;
  8410. };
  8411. Tools.RegisterTopRootEvents = function (events) {
  8412. for (var index = 0; index < events.length; index++) {
  8413. var event = events[index];
  8414. window.addEventListener(event.name, event.handler, false);
  8415. try {
  8416. if (window.parent) {
  8417. window.parent.addEventListener(event.name, event.handler, false);
  8418. }
  8419. }
  8420. catch (e) {
  8421. // Silently fails...
  8422. }
  8423. }
  8424. };
  8425. Tools.UnregisterTopRootEvents = function (events) {
  8426. for (var index = 0; index < events.length; index++) {
  8427. var event = events[index];
  8428. window.removeEventListener(event.name, event.handler);
  8429. try {
  8430. if (window.parent) {
  8431. window.parent.removeEventListener(event.name, event.handler);
  8432. }
  8433. }
  8434. catch (e) {
  8435. // Silently fails...
  8436. }
  8437. }
  8438. };
  8439. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8440. if (mimeType === void 0) { mimeType = "image/png"; }
  8441. // Read the contents of the framebuffer
  8442. var numberOfChannelsByLine = width * 4;
  8443. var halfHeight = height / 2;
  8444. //Reading datas from WebGL
  8445. var data = engine.readPixels(0, 0, width, height);
  8446. //To flip image on Y axis.
  8447. for (var i = 0; i < halfHeight; i++) {
  8448. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8449. var currentCell = j + i * numberOfChannelsByLine;
  8450. var targetLine = height - i - 1;
  8451. var targetCell = j + targetLine * numberOfChannelsByLine;
  8452. var temp = data[currentCell];
  8453. data[currentCell] = data[targetCell];
  8454. data[targetCell] = temp;
  8455. }
  8456. }
  8457. // Create a 2D canvas to store the result
  8458. if (!screenshotCanvas) {
  8459. screenshotCanvas = document.createElement('canvas');
  8460. }
  8461. screenshotCanvas.width = width;
  8462. screenshotCanvas.height = height;
  8463. var context = screenshotCanvas.getContext('2d');
  8464. if (context) {
  8465. // Copy the pixels to a 2D canvas
  8466. var imageData = context.createImageData(width, height);
  8467. var castData = (imageData.data);
  8468. castData.set(data);
  8469. context.putImageData(imageData, 0, 0);
  8470. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8471. }
  8472. };
  8473. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8474. if (mimeType === void 0) { mimeType = "image/png"; }
  8475. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8476. if (successCallback) {
  8477. successCallback(base64Image);
  8478. }
  8479. else {
  8480. // We need HTMLCanvasElement.toBlob for HD screenshots
  8481. if (!screenshotCanvas.toBlob) {
  8482. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8483. screenshotCanvas.toBlob = function (callback, type, quality) {
  8484. var _this = this;
  8485. setTimeout(function () {
  8486. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8487. for (var i = 0; i < len; i++) {
  8488. arr[i] = binStr.charCodeAt(i);
  8489. }
  8490. callback(new Blob([arr], { type: type || 'image/png' }));
  8491. });
  8492. };
  8493. }
  8494. screenshotCanvas.toBlob(function (blob) {
  8495. var url = URL.createObjectURL(blob);
  8496. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8497. if (("download" in document.createElement("a"))) {
  8498. var a = window.document.createElement("a");
  8499. a.href = url;
  8500. if (fileName) {
  8501. a.setAttribute("download", fileName);
  8502. }
  8503. else {
  8504. var date = new Date();
  8505. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8506. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8507. }
  8508. window.document.body.appendChild(a);
  8509. a.addEventListener("click", function () {
  8510. if (a.parentElement) {
  8511. a.parentElement.removeChild(a);
  8512. }
  8513. });
  8514. a.click();
  8515. }
  8516. else {
  8517. var newWindow = window.open("");
  8518. if (!newWindow)
  8519. return;
  8520. var img = newWindow.document.createElement("img");
  8521. img.onload = function () {
  8522. // no longer need to read the blob so it's revoked
  8523. URL.revokeObjectURL(url);
  8524. };
  8525. img.src = url;
  8526. newWindow.document.body.appendChild(img);
  8527. }
  8528. });
  8529. }
  8530. };
  8531. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8532. if (mimeType === void 0) { mimeType = "image/png"; }
  8533. var width;
  8534. var height;
  8535. // If a precision value is specified
  8536. if (size.precision) {
  8537. width = Math.round(engine.getRenderWidth() * size.precision);
  8538. height = Math.round(width / engine.getAspectRatio(camera));
  8539. }
  8540. else if (size.width && size.height) {
  8541. width = size.width;
  8542. height = size.height;
  8543. }
  8544. else if (size.width && !size.height) {
  8545. width = size.width;
  8546. height = Math.round(width / engine.getAspectRatio(camera));
  8547. }
  8548. else if (size.height && !size.width) {
  8549. height = size.height;
  8550. width = Math.round(height * engine.getAspectRatio(camera));
  8551. }
  8552. else if (!isNaN(size)) {
  8553. height = size;
  8554. width = size;
  8555. }
  8556. else {
  8557. Tools.Error("Invalid 'size' parameter !");
  8558. return;
  8559. }
  8560. if (!screenshotCanvas) {
  8561. screenshotCanvas = document.createElement('canvas');
  8562. }
  8563. screenshotCanvas.width = width;
  8564. screenshotCanvas.height = height;
  8565. var renderContext = screenshotCanvas.getContext("2d");
  8566. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8567. var newWidth = width;
  8568. var newHeight = newWidth / ratio;
  8569. if (newHeight > height) {
  8570. newHeight = height;
  8571. newWidth = newHeight * ratio;
  8572. }
  8573. var offsetX = Math.max(0, width - newWidth) / 2;
  8574. var offsetY = Math.max(0, height - newHeight) / 2;
  8575. var renderingCanvas = engine.getRenderingCanvas();
  8576. if (renderContext && renderingCanvas) {
  8577. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8578. }
  8579. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8580. };
  8581. /**
  8582. * Generates an image screenshot from the specified camera.
  8583. *
  8584. * @param engine The engine to use for rendering
  8585. * @param camera The camera to use for rendering
  8586. * @param size This parameter can be set to a single number or to an object with the
  8587. * following (optional) properties: precision, width, height. If a single number is passed,
  8588. * it will be used for both width and height. If an object is passed, the screenshot size
  8589. * will be derived from the parameters. The precision property is a multiplier allowing
  8590. * rendering at a higher or lower resolution.
  8591. * @param successCallback The callback receives a single parameter which contains the
  8592. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8593. * src parameter of an <img> to display it.
  8594. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8595. * Check your browser for supported MIME types.
  8596. * @param samples Texture samples (default: 1)
  8597. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8598. * @param fileName A name for for the downloaded file.
  8599. * @constructor
  8600. */
  8601. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8602. if (mimeType === void 0) { mimeType = "image/png"; }
  8603. if (samples === void 0) { samples = 1; }
  8604. if (antialiasing === void 0) { antialiasing = false; }
  8605. var width;
  8606. var height;
  8607. //If a precision value is specified
  8608. if (size.precision) {
  8609. width = Math.round(engine.getRenderWidth() * size.precision);
  8610. height = Math.round(width / engine.getAspectRatio(camera));
  8611. size = { width: width, height: height };
  8612. }
  8613. else if (size.width && size.height) {
  8614. width = size.width;
  8615. height = size.height;
  8616. }
  8617. else if (size.width && !size.height) {
  8618. width = size.width;
  8619. height = Math.round(width / engine.getAspectRatio(camera));
  8620. size = { width: width, height: height };
  8621. }
  8622. else if (size.height && !size.width) {
  8623. height = size.height;
  8624. width = Math.round(height * engine.getAspectRatio(camera));
  8625. size = { width: width, height: height };
  8626. }
  8627. else if (!isNaN(size)) {
  8628. height = size;
  8629. width = size;
  8630. }
  8631. else {
  8632. Tools.Error("Invalid 'size' parameter !");
  8633. return;
  8634. }
  8635. var scene = camera.getScene();
  8636. var previousCamera = null;
  8637. if (scene.activeCamera !== camera) {
  8638. previousCamera = scene.activeCamera;
  8639. scene.activeCamera = camera;
  8640. }
  8641. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8642. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8643. texture.renderList = null;
  8644. texture.samples = samples;
  8645. if (antialiasing) {
  8646. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8647. }
  8648. texture.onAfterRenderObservable.add(function () {
  8649. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8650. });
  8651. scene.incrementRenderId();
  8652. scene.resetCachedMaterial();
  8653. texture.render(true);
  8654. texture.dispose();
  8655. if (previousCamera) {
  8656. scene.activeCamera = previousCamera;
  8657. }
  8658. camera.getProjectionMatrix(true); // Force cache refresh;
  8659. };
  8660. // XHR response validator for local file scenario
  8661. Tools.ValidateXHRData = function (xhr, dataType) {
  8662. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8663. if (dataType === void 0) { dataType = 7; }
  8664. try {
  8665. if (dataType & 1) {
  8666. if (xhr.responseText && xhr.responseText.length > 0) {
  8667. return true;
  8668. }
  8669. else if (dataType === 1) {
  8670. return false;
  8671. }
  8672. }
  8673. if (dataType & 2) {
  8674. // Check header width and height since there is no "TGA" magic number
  8675. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8676. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8677. return true;
  8678. }
  8679. else if (dataType === 2) {
  8680. return false;
  8681. }
  8682. }
  8683. if (dataType & 4) {
  8684. // Check for the "DDS" magic number
  8685. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8686. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8687. return true;
  8688. }
  8689. else {
  8690. return false;
  8691. }
  8692. }
  8693. }
  8694. catch (e) {
  8695. // Global protection
  8696. }
  8697. return false;
  8698. };
  8699. /**
  8700. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8701. * Be aware Math.random() could cause collisions, but:
  8702. * "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"
  8703. */
  8704. Tools.RandomId = function () {
  8705. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8706. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8707. return v.toString(16);
  8708. });
  8709. };
  8710. /**
  8711. * Test if the given uri is a base64 string.
  8712. * @param uri The uri to test
  8713. * @return True if the uri is a base64 string or false otherwise.
  8714. */
  8715. Tools.IsBase64 = function (uri) {
  8716. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8717. };
  8718. /**
  8719. * Decode the given base64 uri.
  8720. * @param uri The uri to decode
  8721. * @return The decoded base64 data.
  8722. */
  8723. Tools.DecodeBase64 = function (uri) {
  8724. var decodedString = atob(uri.split(",")[1]);
  8725. var bufferLength = decodedString.length;
  8726. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8727. for (var i = 0; i < bufferLength; i++) {
  8728. bufferView[i] = decodedString.charCodeAt(i);
  8729. }
  8730. return bufferView.buffer;
  8731. };
  8732. Object.defineProperty(Tools, "NoneLogLevel", {
  8733. get: function () {
  8734. return Tools._NoneLogLevel;
  8735. },
  8736. enumerable: true,
  8737. configurable: true
  8738. });
  8739. Object.defineProperty(Tools, "MessageLogLevel", {
  8740. get: function () {
  8741. return Tools._MessageLogLevel;
  8742. },
  8743. enumerable: true,
  8744. configurable: true
  8745. });
  8746. Object.defineProperty(Tools, "WarningLogLevel", {
  8747. get: function () {
  8748. return Tools._WarningLogLevel;
  8749. },
  8750. enumerable: true,
  8751. configurable: true
  8752. });
  8753. Object.defineProperty(Tools, "ErrorLogLevel", {
  8754. get: function () {
  8755. return Tools._ErrorLogLevel;
  8756. },
  8757. enumerable: true,
  8758. configurable: true
  8759. });
  8760. Object.defineProperty(Tools, "AllLogLevel", {
  8761. get: function () {
  8762. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8763. },
  8764. enumerable: true,
  8765. configurable: true
  8766. });
  8767. Tools._AddLogEntry = function (entry) {
  8768. Tools._LogCache = entry + Tools._LogCache;
  8769. if (Tools.OnNewCacheEntry) {
  8770. Tools.OnNewCacheEntry(entry);
  8771. }
  8772. };
  8773. Tools._FormatMessage = function (message) {
  8774. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8775. var date = new Date();
  8776. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8777. };
  8778. Tools._LogDisabled = function (message) {
  8779. // nothing to do
  8780. };
  8781. Tools._LogEnabled = function (message) {
  8782. var formattedMessage = Tools._FormatMessage(message);
  8783. console.log("BJS - " + formattedMessage);
  8784. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8785. Tools._AddLogEntry(entry);
  8786. };
  8787. Tools._WarnDisabled = function (message) {
  8788. // nothing to do
  8789. };
  8790. Tools._WarnEnabled = function (message) {
  8791. var formattedMessage = Tools._FormatMessage(message);
  8792. console.warn("BJS - " + formattedMessage);
  8793. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8794. Tools._AddLogEntry(entry);
  8795. };
  8796. Tools._ErrorDisabled = function (message) {
  8797. // nothing to do
  8798. };
  8799. Tools._ErrorEnabled = function (message) {
  8800. Tools.errorsCount++;
  8801. var formattedMessage = Tools._FormatMessage(message);
  8802. console.error("BJS - " + formattedMessage);
  8803. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8804. Tools._AddLogEntry(entry);
  8805. };
  8806. Object.defineProperty(Tools, "LogCache", {
  8807. get: function () {
  8808. return Tools._LogCache;
  8809. },
  8810. enumerable: true,
  8811. configurable: true
  8812. });
  8813. Tools.ClearLogCache = function () {
  8814. Tools._LogCache = "";
  8815. Tools.errorsCount = 0;
  8816. };
  8817. Object.defineProperty(Tools, "LogLevels", {
  8818. set: function (level) {
  8819. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8820. Tools.Log = Tools._LogEnabled;
  8821. }
  8822. else {
  8823. Tools.Log = Tools._LogDisabled;
  8824. }
  8825. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8826. Tools.Warn = Tools._WarnEnabled;
  8827. }
  8828. else {
  8829. Tools.Warn = Tools._WarnDisabled;
  8830. }
  8831. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8832. Tools.Error = Tools._ErrorEnabled;
  8833. }
  8834. else {
  8835. Tools.Error = Tools._ErrorDisabled;
  8836. }
  8837. },
  8838. enumerable: true,
  8839. configurable: true
  8840. });
  8841. Tools.IsWindowObjectExist = function () {
  8842. return (typeof window) !== "undefined";
  8843. };
  8844. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8845. get: function () {
  8846. return Tools._PerformanceNoneLogLevel;
  8847. },
  8848. enumerable: true,
  8849. configurable: true
  8850. });
  8851. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8852. get: function () {
  8853. return Tools._PerformanceUserMarkLogLevel;
  8854. },
  8855. enumerable: true,
  8856. configurable: true
  8857. });
  8858. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8859. get: function () {
  8860. return Tools._PerformanceConsoleLogLevel;
  8861. },
  8862. enumerable: true,
  8863. configurable: true
  8864. });
  8865. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8866. set: function (level) {
  8867. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8868. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8869. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8870. return;
  8871. }
  8872. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8873. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8874. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8875. return;
  8876. }
  8877. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8878. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8879. },
  8880. enumerable: true,
  8881. configurable: true
  8882. });
  8883. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8884. };
  8885. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8886. };
  8887. Tools._StartUserMark = function (counterName, condition) {
  8888. if (condition === void 0) { condition = true; }
  8889. if (!Tools._performance) {
  8890. if (!Tools.IsWindowObjectExist()) {
  8891. return;
  8892. }
  8893. Tools._performance = window.performance;
  8894. }
  8895. if (!condition || !Tools._performance.mark) {
  8896. return;
  8897. }
  8898. Tools._performance.mark(counterName + "-Begin");
  8899. };
  8900. Tools._EndUserMark = function (counterName, condition) {
  8901. if (condition === void 0) { condition = true; }
  8902. if (!condition || !Tools._performance.mark) {
  8903. return;
  8904. }
  8905. Tools._performance.mark(counterName + "-End");
  8906. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8907. };
  8908. Tools._StartPerformanceConsole = function (counterName, condition) {
  8909. if (condition === void 0) { condition = true; }
  8910. if (!condition) {
  8911. return;
  8912. }
  8913. Tools._StartUserMark(counterName, condition);
  8914. if (console.time) {
  8915. console.time(counterName);
  8916. }
  8917. };
  8918. Tools._EndPerformanceConsole = function (counterName, condition) {
  8919. if (condition === void 0) { condition = true; }
  8920. if (!condition) {
  8921. return;
  8922. }
  8923. Tools._EndUserMark(counterName, condition);
  8924. if (console.time) {
  8925. console.timeEnd(counterName);
  8926. }
  8927. };
  8928. Object.defineProperty(Tools, "Now", {
  8929. get: function () {
  8930. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8931. return window.performance.now();
  8932. }
  8933. return new Date().getTime();
  8934. },
  8935. enumerable: true,
  8936. configurable: true
  8937. });
  8938. /**
  8939. * This method will return the name of the class used to create the instance of the given object.
  8940. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8941. * @param object the object to get the class name from
  8942. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8943. */
  8944. Tools.GetClassName = function (object, isType) {
  8945. if (isType === void 0) { isType = false; }
  8946. var name = null;
  8947. if (!isType && object.getClassName) {
  8948. name = object.getClassName();
  8949. }
  8950. else {
  8951. if (object instanceof Object) {
  8952. var classObj = isType ? object : Object.getPrototypeOf(object);
  8953. name = classObj.constructor["__bjsclassName__"];
  8954. }
  8955. if (!name) {
  8956. name = typeof object;
  8957. }
  8958. }
  8959. return name;
  8960. };
  8961. Tools.First = function (array, predicate) {
  8962. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8963. var el = array_1[_i];
  8964. if (predicate(el)) {
  8965. return el;
  8966. }
  8967. }
  8968. return null;
  8969. };
  8970. /**
  8971. * This method will return the name of the full name of the class, including its owning module (if any).
  8972. * 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).
  8973. * @param object the object to get the class name from
  8974. * @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.
  8975. */
  8976. Tools.getFullClassName = function (object, isType) {
  8977. if (isType === void 0) { isType = false; }
  8978. var className = null;
  8979. var moduleName = null;
  8980. if (!isType && object.getClassName) {
  8981. className = object.getClassName();
  8982. }
  8983. else {
  8984. if (object instanceof Object) {
  8985. var classObj = isType ? object : Object.getPrototypeOf(object);
  8986. className = classObj.constructor["__bjsclassName__"];
  8987. moduleName = classObj.constructor["__bjsmoduleName__"];
  8988. }
  8989. if (!className) {
  8990. className = typeof object;
  8991. }
  8992. }
  8993. if (!className) {
  8994. return null;
  8995. }
  8996. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8997. };
  8998. /**
  8999. * 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.
  9000. * @param array
  9001. */
  9002. Tools.arrayOrStringFeeder = function (array) {
  9003. return function (index) {
  9004. if (index >= array.length) {
  9005. return null;
  9006. }
  9007. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9008. if (val && val.getHashCode) {
  9009. val = val.getHashCode();
  9010. }
  9011. if (typeof val === "string") {
  9012. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9013. }
  9014. return val;
  9015. };
  9016. };
  9017. /**
  9018. * Compute the hashCode of a stream of number
  9019. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9020. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9021. * @return the hash code computed
  9022. */
  9023. Tools.hashCodeFromStream = function (feeder) {
  9024. // Based from here: http://stackoverflow.com/a/7616484/802124
  9025. var hash = 0;
  9026. var index = 0;
  9027. var chr = feeder(index++);
  9028. while (chr != null) {
  9029. hash = ((hash << 5) - hash) + chr;
  9030. hash |= 0; // Convert to 32bit integer
  9031. chr = feeder(index++);
  9032. }
  9033. return hash;
  9034. };
  9035. /**
  9036. * Returns a promise that resolves after the given amount of time.
  9037. * @param delay Number of milliseconds to delay
  9038. * @returns Promise that resolves after the given amount of time
  9039. */
  9040. Tools.DelayAsync = function (delay) {
  9041. return new Promise(function (resolve) {
  9042. setTimeout(function () {
  9043. resolve();
  9044. }, delay);
  9045. });
  9046. };
  9047. Tools.BaseUrl = "";
  9048. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9049. /**
  9050. * Default behaviour for cors in the application.
  9051. * It can be a string if the expected behavior is identical in the entire app.
  9052. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9053. */
  9054. Tools.CorsBehavior = "anonymous";
  9055. Tools.UseFallbackTexture = true;
  9056. /**
  9057. * Use this object to register external classes like custom textures or material
  9058. * to allow the laoders to instantiate them
  9059. */
  9060. Tools.RegisteredExternalClasses = {};
  9061. // Used in case of a texture loading problem
  9062. 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";
  9063. Tools.PreprocessUrl = function (url) {
  9064. return url;
  9065. };
  9066. // Logs
  9067. Tools._NoneLogLevel = 0;
  9068. Tools._MessageLogLevel = 1;
  9069. Tools._WarningLogLevel = 2;
  9070. Tools._ErrorLogLevel = 4;
  9071. Tools._LogCache = "";
  9072. Tools.errorsCount = 0;
  9073. Tools.Log = Tools._LogEnabled;
  9074. Tools.Warn = Tools._WarnEnabled;
  9075. Tools.Error = Tools._ErrorEnabled;
  9076. // Performances
  9077. Tools._PerformanceNoneLogLevel = 0;
  9078. Tools._PerformanceUserMarkLogLevel = 1;
  9079. Tools._PerformanceConsoleLogLevel = 2;
  9080. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9081. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9082. return Tools;
  9083. }());
  9084. BABYLON.Tools = Tools;
  9085. /**
  9086. * This class is used to track a performance counter which is number based.
  9087. * The user has access to many properties which give statistics of different nature
  9088. *
  9089. * The implementer can track two kinds of Performance Counter: time and count
  9090. * 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.
  9091. * 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.
  9092. */
  9093. var PerfCounter = /** @class */ (function () {
  9094. function PerfCounter() {
  9095. this._startMonitoringTime = 0;
  9096. this._min = 0;
  9097. this._max = 0;
  9098. this._average = 0;
  9099. this._lastSecAverage = 0;
  9100. this._current = 0;
  9101. this._totalValueCount = 0;
  9102. this._totalAccumulated = 0;
  9103. this._lastSecAccumulated = 0;
  9104. this._lastSecTime = 0;
  9105. this._lastSecValueCount = 0;
  9106. }
  9107. Object.defineProperty(PerfCounter.prototype, "min", {
  9108. /**
  9109. * Returns the smallest value ever
  9110. */
  9111. get: function () {
  9112. return this._min;
  9113. },
  9114. enumerable: true,
  9115. configurable: true
  9116. });
  9117. Object.defineProperty(PerfCounter.prototype, "max", {
  9118. /**
  9119. * Returns the biggest value ever
  9120. */
  9121. get: function () {
  9122. return this._max;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(PerfCounter.prototype, "average", {
  9128. /**
  9129. * Returns the average value since the performance counter is running
  9130. */
  9131. get: function () {
  9132. return this._average;
  9133. },
  9134. enumerable: true,
  9135. configurable: true
  9136. });
  9137. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9138. /**
  9139. * Returns the average value of the last second the counter was monitored
  9140. */
  9141. get: function () {
  9142. return this._lastSecAverage;
  9143. },
  9144. enumerable: true,
  9145. configurable: true
  9146. });
  9147. Object.defineProperty(PerfCounter.prototype, "current", {
  9148. /**
  9149. * Returns the current value
  9150. */
  9151. get: function () {
  9152. return this._current;
  9153. },
  9154. enumerable: true,
  9155. configurable: true
  9156. });
  9157. Object.defineProperty(PerfCounter.prototype, "total", {
  9158. get: function () {
  9159. return this._totalAccumulated;
  9160. },
  9161. enumerable: true,
  9162. configurable: true
  9163. });
  9164. Object.defineProperty(PerfCounter.prototype, "count", {
  9165. get: function () {
  9166. return this._totalValueCount;
  9167. },
  9168. enumerable: true,
  9169. configurable: true
  9170. });
  9171. /**
  9172. * Call this method to start monitoring a new frame.
  9173. * 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.
  9174. */
  9175. PerfCounter.prototype.fetchNewFrame = function () {
  9176. this._totalValueCount++;
  9177. this._current = 0;
  9178. this._lastSecValueCount++;
  9179. };
  9180. /**
  9181. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9182. * @param newCount the count value to add to the monitored count
  9183. * @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.
  9184. */
  9185. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9186. if (!PerfCounter.Enabled) {
  9187. return;
  9188. }
  9189. this._current += newCount;
  9190. if (fetchResult) {
  9191. this._fetchResult();
  9192. }
  9193. };
  9194. /**
  9195. * Start monitoring this performance counter
  9196. */
  9197. PerfCounter.prototype.beginMonitoring = function () {
  9198. if (!PerfCounter.Enabled) {
  9199. return;
  9200. }
  9201. this._startMonitoringTime = Tools.Now;
  9202. };
  9203. /**
  9204. * Compute the time lapsed since the previous beginMonitoring() call.
  9205. * @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
  9206. */
  9207. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9208. if (newFrame === void 0) { newFrame = true; }
  9209. if (!PerfCounter.Enabled) {
  9210. return;
  9211. }
  9212. if (newFrame) {
  9213. this.fetchNewFrame();
  9214. }
  9215. var currentTime = Tools.Now;
  9216. this._current = currentTime - this._startMonitoringTime;
  9217. if (newFrame) {
  9218. this._fetchResult();
  9219. }
  9220. };
  9221. PerfCounter.prototype._fetchResult = function () {
  9222. this._totalAccumulated += this._current;
  9223. this._lastSecAccumulated += this._current;
  9224. // Min/Max update
  9225. this._min = Math.min(this._min, this._current);
  9226. this._max = Math.max(this._max, this._current);
  9227. this._average = this._totalAccumulated / this._totalValueCount;
  9228. // Reset last sec?
  9229. var now = Tools.Now;
  9230. if ((now - this._lastSecTime) > 1000) {
  9231. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9232. this._lastSecTime = now;
  9233. this._lastSecAccumulated = 0;
  9234. this._lastSecValueCount = 0;
  9235. }
  9236. };
  9237. PerfCounter.Enabled = true;
  9238. return PerfCounter;
  9239. }());
  9240. BABYLON.PerfCounter = PerfCounter;
  9241. /**
  9242. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9243. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9244. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9245. * @param name The name of the class, case should be preserved
  9246. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9247. */
  9248. function className(name, module) {
  9249. return function (target) {
  9250. target["__bjsclassName__"] = name;
  9251. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9252. };
  9253. }
  9254. BABYLON.className = className;
  9255. /**
  9256. * An implementation of a loop for asynchronous functions.
  9257. */
  9258. var AsyncLoop = /** @class */ (function () {
  9259. /**
  9260. * Constroctor.
  9261. * @param iterations the number of iterations.
  9262. * @param _fn the function to run each iteration
  9263. * @param _successCallback the callback that will be called upon succesful execution
  9264. * @param offset starting offset.
  9265. */
  9266. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9267. if (offset === void 0) { offset = 0; }
  9268. this.iterations = iterations;
  9269. this._fn = _fn;
  9270. this._successCallback = _successCallback;
  9271. this.index = offset - 1;
  9272. this._done = false;
  9273. }
  9274. /**
  9275. * Execute the next iteration. Must be called after the last iteration was finished.
  9276. */
  9277. AsyncLoop.prototype.executeNext = function () {
  9278. if (!this._done) {
  9279. if (this.index + 1 < this.iterations) {
  9280. ++this.index;
  9281. this._fn(this);
  9282. }
  9283. else {
  9284. this.breakLoop();
  9285. }
  9286. }
  9287. };
  9288. /**
  9289. * Break the loop and run the success callback.
  9290. */
  9291. AsyncLoop.prototype.breakLoop = function () {
  9292. this._done = true;
  9293. this._successCallback();
  9294. };
  9295. /**
  9296. * Helper function
  9297. */
  9298. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9299. if (offset === void 0) { offset = 0; }
  9300. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9301. loop.executeNext();
  9302. return loop;
  9303. };
  9304. /**
  9305. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9306. * @param iterations total number of iterations
  9307. * @param syncedIterations number of synchronous iterations in each async iteration.
  9308. * @param fn the function to call each iteration.
  9309. * @param callback a success call back that will be called when iterating stops.
  9310. * @param breakFunction a break condition (optional)
  9311. * @param timeout timeout settings for the setTimeout function. default - 0.
  9312. * @constructor
  9313. */
  9314. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9315. if (timeout === void 0) { timeout = 0; }
  9316. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9317. if (breakFunction && breakFunction())
  9318. loop.breakLoop();
  9319. else {
  9320. setTimeout(function () {
  9321. for (var i = 0; i < syncedIterations; ++i) {
  9322. var iteration = (loop.index * syncedIterations) + i;
  9323. if (iteration >= iterations)
  9324. break;
  9325. fn(iteration);
  9326. if (breakFunction && breakFunction()) {
  9327. loop.breakLoop();
  9328. break;
  9329. }
  9330. }
  9331. loop.executeNext();
  9332. }, timeout);
  9333. }
  9334. }, callback);
  9335. };
  9336. return AsyncLoop;
  9337. }());
  9338. BABYLON.AsyncLoop = AsyncLoop;
  9339. })(BABYLON || (BABYLON = {}));
  9340. //# sourceMappingURL=babylon.tools.js.map
  9341. var BABYLON;
  9342. (function (BABYLON) {
  9343. var PromiseStates;
  9344. (function (PromiseStates) {
  9345. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9346. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9347. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9348. })(PromiseStates || (PromiseStates = {}));
  9349. var FulFillmentAgregator = /** @class */ (function () {
  9350. function FulFillmentAgregator() {
  9351. this.count = 0;
  9352. this.target = 0;
  9353. this.results = [];
  9354. }
  9355. return FulFillmentAgregator;
  9356. }());
  9357. var InternalPromise = /** @class */ (function () {
  9358. function InternalPromise(resolver) {
  9359. var _this = this;
  9360. this._state = PromiseStates.Pending;
  9361. this._children = new Array();
  9362. this._rejectWasConsumed = false;
  9363. if (!resolver) {
  9364. return;
  9365. }
  9366. try {
  9367. resolver(function (value) {
  9368. _this._resolve(value);
  9369. }, function (reason) {
  9370. _this._reject(reason);
  9371. });
  9372. }
  9373. catch (e) {
  9374. this._reject(e);
  9375. }
  9376. }
  9377. InternalPromise.prototype.catch = function (onRejected) {
  9378. return this.then(undefined, onRejected);
  9379. };
  9380. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9381. var _this = this;
  9382. var newPromise = new InternalPromise();
  9383. newPromise._onFulfilled = onFulfilled;
  9384. newPromise._onRejected = onRejected;
  9385. // Composition
  9386. this._children.push(newPromise);
  9387. if (this._state !== PromiseStates.Pending) {
  9388. BABYLON.Tools.SetImmediate(function () {
  9389. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9390. var returnedValue = newPromise._resolve(_this._result);
  9391. if (returnedValue !== undefined && returnedValue !== null) {
  9392. if (returnedValue._state !== undefined) {
  9393. var returnedPromise = returnedValue;
  9394. newPromise._children.push(returnedPromise);
  9395. newPromise = returnedPromise;
  9396. }
  9397. else {
  9398. newPromise._result = returnedValue;
  9399. }
  9400. }
  9401. }
  9402. else {
  9403. newPromise._reject(_this._reason);
  9404. }
  9405. });
  9406. }
  9407. return newPromise;
  9408. };
  9409. InternalPromise.prototype._moveChildren = function (children) {
  9410. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9411. if (this._state === PromiseStates.Fulfilled) {
  9412. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9413. var child = _b[_i];
  9414. child._resolve(this._result);
  9415. }
  9416. }
  9417. else if (this._state === PromiseStates.Rejected) {
  9418. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9419. var child = _d[_c];
  9420. child._reject(this._reason);
  9421. }
  9422. }
  9423. var _a;
  9424. };
  9425. InternalPromise.prototype._resolve = function (value) {
  9426. try {
  9427. this._state = PromiseStates.Fulfilled;
  9428. this._result = value;
  9429. var returnedValue = null;
  9430. if (this._onFulfilled) {
  9431. returnedValue = this._onFulfilled(value);
  9432. }
  9433. if (returnedValue !== undefined && returnedValue !== null) {
  9434. if (returnedValue._state !== undefined) {
  9435. // Transmit children
  9436. var returnedPromise = returnedValue;
  9437. returnedPromise._moveChildren(this._children);
  9438. }
  9439. else {
  9440. value = returnedValue;
  9441. }
  9442. }
  9443. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9444. var child = _a[_i];
  9445. child._resolve(value);
  9446. }
  9447. this._children.length = 0;
  9448. delete this._onFulfilled;
  9449. delete this._onRejected;
  9450. return returnedValue;
  9451. }
  9452. catch (e) {
  9453. this._reject(e, true);
  9454. }
  9455. return null;
  9456. };
  9457. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9458. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9459. this._state = PromiseStates.Rejected;
  9460. this._reason = reason;
  9461. if (this._onRejected && !onLocalThrow) {
  9462. try {
  9463. this._onRejected(reason);
  9464. this._rejectWasConsumed = true;
  9465. }
  9466. catch (e) {
  9467. reason = e;
  9468. }
  9469. }
  9470. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9471. var child = _a[_i];
  9472. if (this._rejectWasConsumed) {
  9473. child._resolve(null);
  9474. }
  9475. else {
  9476. child._reject(reason);
  9477. }
  9478. }
  9479. this._children.length = 0;
  9480. delete this._onFulfilled;
  9481. delete this._onRejected;
  9482. };
  9483. InternalPromise.resolve = function (value) {
  9484. var newPromise = new InternalPromise();
  9485. newPromise._resolve(value);
  9486. return newPromise;
  9487. };
  9488. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9489. promise.then(function (value) {
  9490. agregator.results[index] = value;
  9491. agregator.count++;
  9492. if (agregator.count === agregator.target) {
  9493. agregator.rootPromise._resolve(agregator.results);
  9494. }
  9495. return null;
  9496. }, function (reason) {
  9497. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9498. agregator.rootPromise._reject(reason);
  9499. }
  9500. });
  9501. };
  9502. InternalPromise.all = function (promises) {
  9503. var newPromise = new InternalPromise();
  9504. var agregator = new FulFillmentAgregator();
  9505. agregator.target = promises.length;
  9506. agregator.rootPromise = newPromise;
  9507. if (promises.length) {
  9508. for (var index = 0; index < promises.length; index++) {
  9509. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9510. }
  9511. }
  9512. else {
  9513. newPromise._resolve([]);
  9514. }
  9515. return newPromise;
  9516. };
  9517. InternalPromise.race = function (promises) {
  9518. var newPromise = new InternalPromise();
  9519. if (promises.length) {
  9520. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9521. var promise = promises_1[_i];
  9522. promise.then(function (value) {
  9523. if (newPromise) {
  9524. newPromise._resolve(value);
  9525. newPromise = null;
  9526. }
  9527. return null;
  9528. }, function (reason) {
  9529. if (newPromise) {
  9530. newPromise._reject(reason);
  9531. newPromise = null;
  9532. }
  9533. });
  9534. }
  9535. }
  9536. return newPromise;
  9537. };
  9538. return InternalPromise;
  9539. }());
  9540. /**
  9541. * Helper class that provides a small promise polyfill
  9542. */
  9543. var PromisePolyfill = /** @class */ (function () {
  9544. function PromisePolyfill() {
  9545. }
  9546. /**
  9547. * Static function used to check if the polyfill is required
  9548. * If this is the case then the function will inject the polyfill to window.Promise
  9549. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9550. */
  9551. PromisePolyfill.Apply = function (force) {
  9552. if (force === void 0) { force = false; }
  9553. if (force || typeof Promise === 'undefined') {
  9554. var root = window;
  9555. root.Promise = InternalPromise;
  9556. }
  9557. };
  9558. return PromisePolyfill;
  9559. }());
  9560. BABYLON.PromisePolyfill = PromisePolyfill;
  9561. })(BABYLON || (BABYLON = {}));
  9562. //# sourceMappingURL=babylon.promise.js.map
  9563. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9564. var BABYLON;
  9565. (function (BABYLON) {
  9566. /**
  9567. * Helper class to push actions to a pool of workers.
  9568. */
  9569. var WorkerPool = /** @class */ (function () {
  9570. /**
  9571. * Constructor
  9572. * @param workers Array of workers to use for actions
  9573. */
  9574. function WorkerPool(workers) {
  9575. this._pendingActions = new Array();
  9576. this._workerInfos = workers.map(function (worker) { return ({
  9577. worker: worker,
  9578. active: false
  9579. }); });
  9580. }
  9581. /**
  9582. * Terminates all workers and clears any pending actions.
  9583. */
  9584. WorkerPool.prototype.dispose = function () {
  9585. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9586. var workerInfo = _a[_i];
  9587. workerInfo.worker.terminate();
  9588. }
  9589. delete this._workerInfos;
  9590. delete this._pendingActions;
  9591. };
  9592. /**
  9593. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9594. * pended until a worker has completed its action.
  9595. * @param action The action to perform. Call onComplete when the action is complete.
  9596. */
  9597. WorkerPool.prototype.push = function (action) {
  9598. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9599. var workerInfo = _a[_i];
  9600. if (!workerInfo.active) {
  9601. this._execute(workerInfo, action);
  9602. return;
  9603. }
  9604. }
  9605. this._pendingActions.push(action);
  9606. };
  9607. WorkerPool.prototype._execute = function (workerInfo, action) {
  9608. var _this = this;
  9609. workerInfo.active = true;
  9610. action(workerInfo.worker, function () {
  9611. workerInfo.active = false;
  9612. var nextAction = _this._pendingActions.shift();
  9613. if (nextAction) {
  9614. _this._execute(workerInfo, nextAction);
  9615. }
  9616. });
  9617. };
  9618. return WorkerPool;
  9619. }());
  9620. BABYLON.WorkerPool = WorkerPool;
  9621. })(BABYLON || (BABYLON = {}));
  9622. //# sourceMappingURL=babylon.workerPool.js.map
  9623. var BABYLON;
  9624. (function (BABYLON) {
  9625. var _AlphaState = /** @class */ (function () {
  9626. /**
  9627. * Initializes the state.
  9628. */
  9629. function _AlphaState() {
  9630. this._isAlphaBlendDirty = false;
  9631. this._isBlendFunctionParametersDirty = false;
  9632. this._isBlendEquationParametersDirty = false;
  9633. this._isBlendConstantsDirty = false;
  9634. this._alphaBlend = false;
  9635. this._blendFunctionParameters = new Array(4);
  9636. this._blendEquationParameters = new Array(2);
  9637. this._blendConstants = new Array(4);
  9638. this.reset();
  9639. }
  9640. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9641. get: function () {
  9642. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9643. },
  9644. enumerable: true,
  9645. configurable: true
  9646. });
  9647. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9648. get: function () {
  9649. return this._alphaBlend;
  9650. },
  9651. set: function (value) {
  9652. if (this._alphaBlend === value) {
  9653. return;
  9654. }
  9655. this._alphaBlend = value;
  9656. this._isAlphaBlendDirty = true;
  9657. },
  9658. enumerable: true,
  9659. configurable: true
  9660. });
  9661. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9662. if (this._blendConstants[0] === r &&
  9663. this._blendConstants[1] === g &&
  9664. this._blendConstants[2] === b &&
  9665. this._blendConstants[3] === a) {
  9666. return;
  9667. }
  9668. this._blendConstants[0] = r;
  9669. this._blendConstants[1] = g;
  9670. this._blendConstants[2] = b;
  9671. this._blendConstants[3] = a;
  9672. this._isBlendConstantsDirty = true;
  9673. };
  9674. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9675. if (this._blendFunctionParameters[0] === value0 &&
  9676. this._blendFunctionParameters[1] === value1 &&
  9677. this._blendFunctionParameters[2] === value2 &&
  9678. this._blendFunctionParameters[3] === value3) {
  9679. return;
  9680. }
  9681. this._blendFunctionParameters[0] = value0;
  9682. this._blendFunctionParameters[1] = value1;
  9683. this._blendFunctionParameters[2] = value2;
  9684. this._blendFunctionParameters[3] = value3;
  9685. this._isBlendFunctionParametersDirty = true;
  9686. };
  9687. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9688. if (this._blendEquationParameters[0] === rgb &&
  9689. this._blendEquationParameters[1] === alpha) {
  9690. return;
  9691. }
  9692. this._blendEquationParameters[0] = rgb;
  9693. this._blendEquationParameters[1] = alpha;
  9694. this._isBlendEquationParametersDirty = true;
  9695. };
  9696. _AlphaState.prototype.reset = function () {
  9697. this._alphaBlend = false;
  9698. this._blendFunctionParameters[0] = null;
  9699. this._blendFunctionParameters[1] = null;
  9700. this._blendFunctionParameters[2] = null;
  9701. this._blendFunctionParameters[3] = null;
  9702. this._blendEquationParameters[0] = null;
  9703. this._blendEquationParameters[1] = null;
  9704. this._blendConstants[0] = null;
  9705. this._blendConstants[1] = null;
  9706. this._blendConstants[2] = null;
  9707. this._blendConstants[3] = null;
  9708. this._isAlphaBlendDirty = true;
  9709. this._isBlendFunctionParametersDirty = false;
  9710. this._isBlendEquationParametersDirty = false;
  9711. this._isBlendConstantsDirty = false;
  9712. };
  9713. _AlphaState.prototype.apply = function (gl) {
  9714. if (!this.isDirty) {
  9715. return;
  9716. }
  9717. // Alpha blend
  9718. if (this._isAlphaBlendDirty) {
  9719. if (this._alphaBlend) {
  9720. gl.enable(gl.BLEND);
  9721. }
  9722. else {
  9723. gl.disable(gl.BLEND);
  9724. }
  9725. this._isAlphaBlendDirty = false;
  9726. }
  9727. // Alpha function
  9728. if (this._isBlendFunctionParametersDirty) {
  9729. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9730. this._isBlendFunctionParametersDirty = false;
  9731. }
  9732. // Alpha equation
  9733. if (this._isBlendEquationParametersDirty) {
  9734. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9735. this._isBlendEquationParametersDirty = false;
  9736. }
  9737. // Constants
  9738. if (this._isBlendConstantsDirty) {
  9739. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9740. this._isBlendConstantsDirty = false;
  9741. }
  9742. };
  9743. return _AlphaState;
  9744. }());
  9745. BABYLON._AlphaState = _AlphaState;
  9746. })(BABYLON || (BABYLON = {}));
  9747. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9748. var BABYLON;
  9749. (function (BABYLON) {
  9750. var _DepthCullingState = /** @class */ (function () {
  9751. /**
  9752. * Initializes the state.
  9753. */
  9754. function _DepthCullingState() {
  9755. this._isDepthTestDirty = false;
  9756. this._isDepthMaskDirty = false;
  9757. this._isDepthFuncDirty = false;
  9758. this._isCullFaceDirty = false;
  9759. this._isCullDirty = false;
  9760. this._isZOffsetDirty = false;
  9761. this._isFrontFaceDirty = false;
  9762. this.reset();
  9763. }
  9764. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9765. get: function () {
  9766. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9772. get: function () {
  9773. return this._zOffset;
  9774. },
  9775. set: function (value) {
  9776. if (this._zOffset === value) {
  9777. return;
  9778. }
  9779. this._zOffset = value;
  9780. this._isZOffsetDirty = true;
  9781. },
  9782. enumerable: true,
  9783. configurable: true
  9784. });
  9785. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9786. get: function () {
  9787. return this._cullFace;
  9788. },
  9789. set: function (value) {
  9790. if (this._cullFace === value) {
  9791. return;
  9792. }
  9793. this._cullFace = value;
  9794. this._isCullFaceDirty = true;
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9800. get: function () {
  9801. return this._cull;
  9802. },
  9803. set: function (value) {
  9804. if (this._cull === value) {
  9805. return;
  9806. }
  9807. this._cull = value;
  9808. this._isCullDirty = true;
  9809. },
  9810. enumerable: true,
  9811. configurable: true
  9812. });
  9813. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9814. get: function () {
  9815. return this._depthFunc;
  9816. },
  9817. set: function (value) {
  9818. if (this._depthFunc === value) {
  9819. return;
  9820. }
  9821. this._depthFunc = value;
  9822. this._isDepthFuncDirty = true;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9828. get: function () {
  9829. return this._depthMask;
  9830. },
  9831. set: function (value) {
  9832. if (this._depthMask === value) {
  9833. return;
  9834. }
  9835. this._depthMask = value;
  9836. this._isDepthMaskDirty = true;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9842. get: function () {
  9843. return this._depthTest;
  9844. },
  9845. set: function (value) {
  9846. if (this._depthTest === value) {
  9847. return;
  9848. }
  9849. this._depthTest = value;
  9850. this._isDepthTestDirty = true;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9856. get: function () {
  9857. return this._frontFace;
  9858. },
  9859. set: function (value) {
  9860. if (this._frontFace === value) {
  9861. return;
  9862. }
  9863. this._frontFace = value;
  9864. this._isFrontFaceDirty = true;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. _DepthCullingState.prototype.reset = function () {
  9870. this._depthMask = true;
  9871. this._depthTest = true;
  9872. this._depthFunc = null;
  9873. this._cullFace = null;
  9874. this._cull = null;
  9875. this._zOffset = 0;
  9876. this._frontFace = null;
  9877. this._isDepthTestDirty = true;
  9878. this._isDepthMaskDirty = true;
  9879. this._isDepthFuncDirty = false;
  9880. this._isCullFaceDirty = false;
  9881. this._isCullDirty = false;
  9882. this._isZOffsetDirty = false;
  9883. this._isFrontFaceDirty = false;
  9884. };
  9885. _DepthCullingState.prototype.apply = function (gl) {
  9886. if (!this.isDirty) {
  9887. return;
  9888. }
  9889. // Cull
  9890. if (this._isCullDirty) {
  9891. if (this.cull) {
  9892. gl.enable(gl.CULL_FACE);
  9893. }
  9894. else {
  9895. gl.disable(gl.CULL_FACE);
  9896. }
  9897. this._isCullDirty = false;
  9898. }
  9899. // Cull face
  9900. if (this._isCullFaceDirty) {
  9901. gl.cullFace(this.cullFace);
  9902. this._isCullFaceDirty = false;
  9903. }
  9904. // Depth mask
  9905. if (this._isDepthMaskDirty) {
  9906. gl.depthMask(this.depthMask);
  9907. this._isDepthMaskDirty = false;
  9908. }
  9909. // Depth test
  9910. if (this._isDepthTestDirty) {
  9911. if (this.depthTest) {
  9912. gl.enable(gl.DEPTH_TEST);
  9913. }
  9914. else {
  9915. gl.disable(gl.DEPTH_TEST);
  9916. }
  9917. this._isDepthTestDirty = false;
  9918. }
  9919. // Depth func
  9920. if (this._isDepthFuncDirty) {
  9921. gl.depthFunc(this.depthFunc);
  9922. this._isDepthFuncDirty = false;
  9923. }
  9924. // zOffset
  9925. if (this._isZOffsetDirty) {
  9926. if (this.zOffset) {
  9927. gl.enable(gl.POLYGON_OFFSET_FILL);
  9928. gl.polygonOffset(this.zOffset, 0);
  9929. }
  9930. else {
  9931. gl.disable(gl.POLYGON_OFFSET_FILL);
  9932. }
  9933. this._isZOffsetDirty = false;
  9934. }
  9935. // Front face
  9936. if (this._isFrontFaceDirty) {
  9937. gl.frontFace(this.frontFace);
  9938. this._isFrontFaceDirty = false;
  9939. }
  9940. };
  9941. return _DepthCullingState;
  9942. }());
  9943. BABYLON._DepthCullingState = _DepthCullingState;
  9944. })(BABYLON || (BABYLON = {}));
  9945. //# sourceMappingURL=babylon.depthCullingState.js.map
  9946. var BABYLON;
  9947. (function (BABYLON) {
  9948. var _StencilState = /** @class */ (function () {
  9949. function _StencilState() {
  9950. this._isStencilTestDirty = false;
  9951. this._isStencilMaskDirty = false;
  9952. this._isStencilFuncDirty = false;
  9953. this._isStencilOpDirty = false;
  9954. this.reset();
  9955. }
  9956. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9957. get: function () {
  9958. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9959. },
  9960. enumerable: true,
  9961. configurable: true
  9962. });
  9963. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9964. get: function () {
  9965. return this._stencilFunc;
  9966. },
  9967. set: function (value) {
  9968. if (this._stencilFunc === value) {
  9969. return;
  9970. }
  9971. this._stencilFunc = value;
  9972. this._isStencilFuncDirty = true;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9978. get: function () {
  9979. return this._stencilFuncRef;
  9980. },
  9981. set: function (value) {
  9982. if (this._stencilFuncRef === value) {
  9983. return;
  9984. }
  9985. this._stencilFuncRef = value;
  9986. this._isStencilFuncDirty = true;
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9992. get: function () {
  9993. return this._stencilFuncMask;
  9994. },
  9995. set: function (value) {
  9996. if (this._stencilFuncMask === value) {
  9997. return;
  9998. }
  9999. this._stencilFuncMask = value;
  10000. this._isStencilFuncDirty = true;
  10001. },
  10002. enumerable: true,
  10003. configurable: true
  10004. });
  10005. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10006. get: function () {
  10007. return this._stencilOpStencilFail;
  10008. },
  10009. set: function (value) {
  10010. if (this._stencilOpStencilFail === value) {
  10011. return;
  10012. }
  10013. this._stencilOpStencilFail = value;
  10014. this._isStencilOpDirty = true;
  10015. },
  10016. enumerable: true,
  10017. configurable: true
  10018. });
  10019. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10020. get: function () {
  10021. return this._stencilOpDepthFail;
  10022. },
  10023. set: function (value) {
  10024. if (this._stencilOpDepthFail === value) {
  10025. return;
  10026. }
  10027. this._stencilOpDepthFail = value;
  10028. this._isStencilOpDirty = true;
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10034. get: function () {
  10035. return this._stencilOpStencilDepthPass;
  10036. },
  10037. set: function (value) {
  10038. if (this._stencilOpStencilDepthPass === value) {
  10039. return;
  10040. }
  10041. this._stencilOpStencilDepthPass = value;
  10042. this._isStencilOpDirty = true;
  10043. },
  10044. enumerable: true,
  10045. configurable: true
  10046. });
  10047. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10048. get: function () {
  10049. return this._stencilMask;
  10050. },
  10051. set: function (value) {
  10052. if (this._stencilMask === value) {
  10053. return;
  10054. }
  10055. this._stencilMask = value;
  10056. this._isStencilMaskDirty = true;
  10057. },
  10058. enumerable: true,
  10059. configurable: true
  10060. });
  10061. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10062. get: function () {
  10063. return this._stencilTest;
  10064. },
  10065. set: function (value) {
  10066. if (this._stencilTest === value) {
  10067. return;
  10068. }
  10069. this._stencilTest = value;
  10070. this._isStencilTestDirty = true;
  10071. },
  10072. enumerable: true,
  10073. configurable: true
  10074. });
  10075. _StencilState.prototype.reset = function () {
  10076. this._stencilTest = false;
  10077. this._stencilMask = 0xFF;
  10078. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10079. this._stencilFuncRef = 1;
  10080. this._stencilFuncMask = 0xFF;
  10081. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10082. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10083. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10084. this._isStencilTestDirty = true;
  10085. this._isStencilMaskDirty = true;
  10086. this._isStencilFuncDirty = true;
  10087. this._isStencilOpDirty = true;
  10088. };
  10089. _StencilState.prototype.apply = function (gl) {
  10090. if (!this.isDirty) {
  10091. return;
  10092. }
  10093. // Stencil test
  10094. if (this._isStencilTestDirty) {
  10095. if (this.stencilTest) {
  10096. gl.enable(gl.STENCIL_TEST);
  10097. }
  10098. else {
  10099. gl.disable(gl.STENCIL_TEST);
  10100. }
  10101. this._isStencilTestDirty = false;
  10102. }
  10103. // Stencil mask
  10104. if (this._isStencilMaskDirty) {
  10105. gl.stencilMask(this.stencilMask);
  10106. this._isStencilMaskDirty = false;
  10107. }
  10108. // Stencil func
  10109. if (this._isStencilFuncDirty) {
  10110. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10111. this._isStencilFuncDirty = false;
  10112. }
  10113. // Stencil op
  10114. if (this._isStencilOpDirty) {
  10115. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10116. this._isStencilOpDirty = false;
  10117. }
  10118. };
  10119. return _StencilState;
  10120. }());
  10121. BABYLON._StencilState = _StencilState;
  10122. })(BABYLON || (BABYLON = {}));
  10123. //# sourceMappingURL=babylon.stencilState.js.map
  10124. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10125. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10126. s = arguments[i];
  10127. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10128. t[p] = s[p];
  10129. }
  10130. return t;
  10131. };
  10132. var BABYLON;
  10133. (function (BABYLON) {
  10134. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10135. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10136. };
  10137. var compileRawShader = function (gl, source, type) {
  10138. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10139. gl.shaderSource(shader, source);
  10140. gl.compileShader(shader);
  10141. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10142. var log = gl.getShaderInfoLog(shader);
  10143. if (log) {
  10144. throw new Error(log);
  10145. }
  10146. }
  10147. if (!shader) {
  10148. throw new Error("Something went wrong while compile the shader.");
  10149. }
  10150. return shader;
  10151. };
  10152. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10153. var magFilter = gl.NEAREST;
  10154. var minFilter = gl.NEAREST;
  10155. switch (samplingMode) {
  10156. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10157. magFilter = gl.LINEAR;
  10158. if (generateMipMaps) {
  10159. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10160. }
  10161. else {
  10162. minFilter = gl.LINEAR;
  10163. }
  10164. break;
  10165. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10166. magFilter = gl.LINEAR;
  10167. if (generateMipMaps) {
  10168. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10169. }
  10170. else {
  10171. minFilter = gl.LINEAR;
  10172. }
  10173. break;
  10174. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10175. magFilter = gl.NEAREST;
  10176. if (generateMipMaps) {
  10177. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10178. }
  10179. else {
  10180. minFilter = gl.NEAREST;
  10181. }
  10182. break;
  10183. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10184. magFilter = gl.NEAREST;
  10185. if (generateMipMaps) {
  10186. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10187. }
  10188. else {
  10189. minFilter = gl.NEAREST;
  10190. }
  10191. break;
  10192. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10193. magFilter = gl.NEAREST;
  10194. if (generateMipMaps) {
  10195. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10196. }
  10197. else {
  10198. minFilter = gl.LINEAR;
  10199. }
  10200. break;
  10201. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10202. magFilter = gl.NEAREST;
  10203. if (generateMipMaps) {
  10204. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10205. }
  10206. else {
  10207. minFilter = gl.LINEAR;
  10208. }
  10209. break;
  10210. case BABYLON.Texture.NEAREST_LINEAR:
  10211. magFilter = gl.NEAREST;
  10212. minFilter = gl.LINEAR;
  10213. break;
  10214. case BABYLON.Texture.NEAREST_NEAREST:
  10215. magFilter = gl.NEAREST;
  10216. minFilter = gl.NEAREST;
  10217. break;
  10218. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10219. magFilter = gl.LINEAR;
  10220. if (generateMipMaps) {
  10221. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10222. }
  10223. else {
  10224. minFilter = gl.NEAREST;
  10225. }
  10226. break;
  10227. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10228. magFilter = gl.LINEAR;
  10229. if (generateMipMaps) {
  10230. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10231. }
  10232. else {
  10233. minFilter = gl.NEAREST;
  10234. }
  10235. break;
  10236. case BABYLON.Texture.LINEAR_LINEAR:
  10237. magFilter = gl.LINEAR;
  10238. minFilter = gl.LINEAR;
  10239. break;
  10240. case BABYLON.Texture.LINEAR_NEAREST:
  10241. magFilter = gl.LINEAR;
  10242. minFilter = gl.NEAREST;
  10243. break;
  10244. }
  10245. return {
  10246. min: minFilter,
  10247. mag: magFilter
  10248. };
  10249. };
  10250. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10251. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10252. var img;
  10253. var onload = function () {
  10254. loadedImages[index] = img;
  10255. loadedImages._internalCount++;
  10256. if (scene) {
  10257. scene._removePendingData(img);
  10258. }
  10259. if (loadedImages._internalCount === 6) {
  10260. onfinish(loadedImages);
  10261. }
  10262. };
  10263. var onerror = function (message, exception) {
  10264. if (scene) {
  10265. scene._removePendingData(img);
  10266. }
  10267. if (onErrorCallBack) {
  10268. onErrorCallBack(message, exception);
  10269. }
  10270. };
  10271. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10272. if (scene) {
  10273. scene._addPendingData(img);
  10274. }
  10275. };
  10276. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10277. if (onError === void 0) { onError = null; }
  10278. var loadedImages = [];
  10279. loadedImages._internalCount = 0;
  10280. for (var index = 0; index < 6; index++) {
  10281. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10282. }
  10283. };
  10284. var BufferPointer = /** @class */ (function () {
  10285. function BufferPointer() {
  10286. }
  10287. return BufferPointer;
  10288. }());
  10289. var InstancingAttributeInfo = /** @class */ (function () {
  10290. function InstancingAttributeInfo() {
  10291. }
  10292. return InstancingAttributeInfo;
  10293. }());
  10294. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10295. /**
  10296. * Define options used to create a render target texture
  10297. */
  10298. var RenderTargetCreationOptions = /** @class */ (function () {
  10299. function RenderTargetCreationOptions() {
  10300. }
  10301. return RenderTargetCreationOptions;
  10302. }());
  10303. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10304. /**
  10305. * Define options used to create a depth texture
  10306. */
  10307. var DepthTextureCreationOptions = /** @class */ (function () {
  10308. function DepthTextureCreationOptions() {
  10309. }
  10310. return DepthTextureCreationOptions;
  10311. }());
  10312. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10313. /**
  10314. * Regroup several parameters relative to the browser in use
  10315. */
  10316. var EngineCapabilities = /** @class */ (function () {
  10317. function EngineCapabilities() {
  10318. }
  10319. return EngineCapabilities;
  10320. }());
  10321. BABYLON.EngineCapabilities = EngineCapabilities;
  10322. /**
  10323. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10324. */
  10325. var Engine = /** @class */ (function () {
  10326. /**
  10327. * @constructor
  10328. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10329. * @param antialias defines enable antialiasing (default: false)
  10330. * @param options defines further options to be sent to the getContext() function
  10331. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10332. */
  10333. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10334. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10335. var _this = this;
  10336. // Public members
  10337. this.forcePOTTextures = false;
  10338. this.isFullscreen = false;
  10339. this.isPointerLock = false;
  10340. this.cullBackFaces = true;
  10341. this.renderEvenInBackground = true;
  10342. this.preventCacheWipeBetweenFrames = false;
  10343. // To enable/disable IDB support and avoid XHR on .manifest
  10344. this.enableOfflineSupport = false;
  10345. this.scenes = new Array();
  10346. this.postProcesses = new Array();
  10347. // Observables
  10348. /**
  10349. * Observable event triggered each time the rendering canvas is resized
  10350. */
  10351. this.onResizeObservable = new BABYLON.Observable();
  10352. /**
  10353. * Observable event triggered each time the canvas loses focus
  10354. */
  10355. this.onCanvasBlurObservable = new BABYLON.Observable();
  10356. /**
  10357. * Observable event triggered each time the canvas gains focus
  10358. */
  10359. this.onCanvasFocusObservable = new BABYLON.Observable();
  10360. /**
  10361. * Observable event triggered each time the canvas receives pointerout event
  10362. */
  10363. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10364. /**
  10365. * Observable event triggered before each texture is initialized
  10366. */
  10367. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10368. //WebVR
  10369. this._vrDisplay = undefined;
  10370. this._vrSupported = false;
  10371. this._vrExclusivePointerMode = false;
  10372. // Uniform buffers list
  10373. this.disableUniformBuffers = false;
  10374. this._uniformBuffers = new Array();
  10375. // Observables
  10376. /**
  10377. * Observable raised when the engine begins a new frame
  10378. */
  10379. this.onBeginFrameObservable = new BABYLON.Observable();
  10380. /**
  10381. * Observable raised when the engine ends the current frame
  10382. */
  10383. this.onEndFrameObservable = new BABYLON.Observable();
  10384. /**
  10385. * Observable raised when the engine is about to compile a shader
  10386. */
  10387. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10388. /**
  10389. * Observable raised when the engine has jsut compiled a shader
  10390. */
  10391. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10392. this._windowIsBackground = false;
  10393. this._webGLVersion = 1.0;
  10394. this._badOS = false;
  10395. this._badDesktopOS = false;
  10396. /**
  10397. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10398. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10399. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10400. */
  10401. this.disableTextureBindingOptimization = false;
  10402. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10403. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10404. this.onVRRequestPresentStart = new BABYLON.Observable();
  10405. this._colorWrite = true;
  10406. this._drawCalls = new BABYLON.PerfCounter();
  10407. this._textureCollisions = new BABYLON.PerfCounter();
  10408. this._renderingQueueLaunched = false;
  10409. this._activeRenderLoops = new Array();
  10410. // Deterministic lockstepMaxSteps
  10411. this._deterministicLockstep = false;
  10412. this._lockstepMaxSteps = 4;
  10413. // Lost context
  10414. this.onContextLostObservable = new BABYLON.Observable();
  10415. this.onContextRestoredObservable = new BABYLON.Observable();
  10416. this._contextWasLost = false;
  10417. this._doNotHandleContextLost = false;
  10418. // FPS
  10419. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10420. this._fps = 60;
  10421. this._deltaTime = 0;
  10422. /**
  10423. * Turn this value on if you want to pause FPS computation when in background
  10424. */
  10425. this.disablePerformanceMonitorInBackground = false;
  10426. // States
  10427. this._depthCullingState = new BABYLON._DepthCullingState();
  10428. this._stencilState = new BABYLON._StencilState();
  10429. this._alphaState = new BABYLON._AlphaState();
  10430. this._alphaMode = Engine.ALPHA_DISABLE;
  10431. // Cache
  10432. this._internalTexturesCache = new Array();
  10433. this._activeChannel = 0;
  10434. this._currentTextureChannel = -1;
  10435. this._boundTexturesCache = {};
  10436. this._compiledEffects = {};
  10437. this._vertexAttribArraysEnabled = [];
  10438. this._uintIndicesCurrentlySet = false;
  10439. this._currentBoundBuffer = new Array();
  10440. this._currentBufferPointers = new Array();
  10441. this._currentInstanceLocations = new Array();
  10442. this._currentInstanceBuffers = new Array();
  10443. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10444. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10445. this._vaoRecordInProgress = false;
  10446. this._mustWipeVertexAttributes = false;
  10447. this._nextFreeTextureSlots = new Array();
  10448. this._maxSimultaneousTextures = 0;
  10449. this._activeRequests = new Array();
  10450. // Hardware supported Compressed Textures
  10451. this._texturesSupported = new Array();
  10452. this._onVRFullScreenTriggered = function () {
  10453. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10454. //get the old size before we change
  10455. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10456. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10457. //get the width and height, change the render size
  10458. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10459. _this.setHardwareScalingLevel(1);
  10460. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10461. }
  10462. else {
  10463. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10464. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10465. }
  10466. };
  10467. this._boundUniforms = {};
  10468. // Register promises
  10469. BABYLON.PromisePolyfill.Apply();
  10470. var canvas = null;
  10471. Engine.Instances.push(this);
  10472. if (!canvasOrContext) {
  10473. return;
  10474. }
  10475. options = options || {};
  10476. if (canvasOrContext.getContext) {
  10477. canvas = canvasOrContext;
  10478. this._renderingCanvas = canvas;
  10479. if (antialias != null) {
  10480. options.antialias = antialias;
  10481. }
  10482. if (options.deterministicLockstep === undefined) {
  10483. options.deterministicLockstep = false;
  10484. }
  10485. if (options.lockstepMaxSteps === undefined) {
  10486. options.lockstepMaxSteps = 4;
  10487. }
  10488. if (options.preserveDrawingBuffer === undefined) {
  10489. options.preserveDrawingBuffer = false;
  10490. }
  10491. if (options.audioEngine === undefined) {
  10492. options.audioEngine = true;
  10493. }
  10494. if (options.stencil === undefined) {
  10495. options.stencil = true;
  10496. }
  10497. this._deterministicLockstep = options.deterministicLockstep;
  10498. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10499. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10500. // Exceptions
  10501. if (navigator && navigator.userAgent) {
  10502. var ua = navigator.userAgent;
  10503. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10504. var exception = _a[_i];
  10505. var key = exception.key;
  10506. var targets = exception.targets;
  10507. if (ua.indexOf(key) > -1) {
  10508. if (exception.capture && exception.captureConstraint) {
  10509. var capture = exception.capture;
  10510. var constraint = exception.captureConstraint;
  10511. var regex = new RegExp(capture);
  10512. var matches = regex.exec(ua);
  10513. if (matches && matches.length > 0) {
  10514. var capturedValue = parseInt(matches[matches.length - 1]);
  10515. if (capturedValue >= constraint) {
  10516. continue;
  10517. }
  10518. }
  10519. }
  10520. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10521. var target = targets_1[_b];
  10522. switch (target) {
  10523. case "uniformBuffer":
  10524. this.disableUniformBuffers = true;
  10525. break;
  10526. case "textureBindingOptimization":
  10527. this.disableTextureBindingOptimization = true;
  10528. break;
  10529. }
  10530. }
  10531. }
  10532. }
  10533. }
  10534. // GL
  10535. if (!options.disableWebGL2Support) {
  10536. try {
  10537. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10538. if (this._gl) {
  10539. this._webGLVersion = 2.0;
  10540. }
  10541. }
  10542. catch (e) {
  10543. // Do nothing
  10544. }
  10545. }
  10546. if (!this._gl) {
  10547. if (!canvas) {
  10548. throw new Error("The provided canvas is null or undefined.");
  10549. }
  10550. try {
  10551. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10552. }
  10553. catch (e) {
  10554. throw new Error("WebGL not supported");
  10555. }
  10556. }
  10557. if (!this._gl) {
  10558. throw new Error("WebGL not supported");
  10559. }
  10560. this._onCanvasFocus = function () {
  10561. _this.onCanvasFocusObservable.notifyObservers(_this);
  10562. };
  10563. this._onCanvasBlur = function () {
  10564. _this.onCanvasBlurObservable.notifyObservers(_this);
  10565. };
  10566. canvas.addEventListener("focus", this._onCanvasFocus);
  10567. canvas.addEventListener("blur", this._onCanvasBlur);
  10568. this._onBlur = function () {
  10569. if (_this.disablePerformanceMonitorInBackground) {
  10570. _this._performanceMonitor.disable();
  10571. }
  10572. _this._windowIsBackground = true;
  10573. };
  10574. this._onFocus = function () {
  10575. if (_this.disablePerformanceMonitorInBackground) {
  10576. _this._performanceMonitor.enable();
  10577. }
  10578. _this._windowIsBackground = false;
  10579. };
  10580. this._onCanvasPointerOut = function (ev) {
  10581. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10582. };
  10583. window.addEventListener("blur", this._onBlur);
  10584. window.addEventListener("focus", this._onFocus);
  10585. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10586. // Context lost
  10587. if (!this._doNotHandleContextLost) {
  10588. this._onContextLost = function (evt) {
  10589. evt.preventDefault();
  10590. _this._contextWasLost = true;
  10591. BABYLON.Tools.Warn("WebGL context lost.");
  10592. _this.onContextLostObservable.notifyObservers(_this);
  10593. };
  10594. this._onContextRestored = function (evt) {
  10595. // Adding a timeout to avoid race condition at browser level
  10596. setTimeout(function () {
  10597. // Rebuild gl context
  10598. _this._initGLContext();
  10599. // Rebuild effects
  10600. _this._rebuildEffects();
  10601. // Rebuild textures
  10602. _this._rebuildInternalTextures();
  10603. // Rebuild buffers
  10604. _this._rebuildBuffers();
  10605. // Cache
  10606. _this.wipeCaches(true);
  10607. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10608. _this.onContextRestoredObservable.notifyObservers(_this);
  10609. _this._contextWasLost = false;
  10610. }, 0);
  10611. };
  10612. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10613. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10614. }
  10615. }
  10616. else {
  10617. this._gl = canvasOrContext;
  10618. this._renderingCanvas = this._gl.canvas;
  10619. if (this._gl.renderbufferStorageMultisample) {
  10620. this._webGLVersion = 2.0;
  10621. }
  10622. options.stencil = this._gl.getContextAttributes().stencil;
  10623. }
  10624. // Viewport
  10625. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10626. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10627. this.resize();
  10628. this._isStencilEnable = options.stencil ? true : false;
  10629. this._initGLContext();
  10630. if (canvas) {
  10631. // Fullscreen
  10632. this._onFullscreenChange = function () {
  10633. if (document.fullscreen !== undefined) {
  10634. _this.isFullscreen = document.fullscreen;
  10635. }
  10636. else if (document.mozFullScreen !== undefined) {
  10637. _this.isFullscreen = document.mozFullScreen;
  10638. }
  10639. else if (document.webkitIsFullScreen !== undefined) {
  10640. _this.isFullscreen = document.webkitIsFullScreen;
  10641. }
  10642. else if (document.msIsFullScreen !== undefined) {
  10643. _this.isFullscreen = document.msIsFullScreen;
  10644. }
  10645. // Pointer lock
  10646. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10647. canvas.requestPointerLock = canvas.requestPointerLock ||
  10648. canvas.msRequestPointerLock ||
  10649. canvas.mozRequestPointerLock ||
  10650. canvas.webkitRequestPointerLock;
  10651. if (canvas.requestPointerLock) {
  10652. canvas.requestPointerLock();
  10653. }
  10654. }
  10655. };
  10656. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10657. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10658. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10659. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10660. // Pointer lock
  10661. this._onPointerLockChange = function () {
  10662. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10663. document.webkitPointerLockElement === canvas ||
  10664. document.msPointerLockElement === canvas ||
  10665. document.pointerLockElement === canvas);
  10666. };
  10667. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10668. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10669. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10670. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10671. this._onVRDisplayPointerRestricted = function () {
  10672. if (canvas) {
  10673. canvas.requestPointerLock();
  10674. }
  10675. };
  10676. this._onVRDisplayPointerUnrestricted = function () {
  10677. document.exitPointerLock();
  10678. };
  10679. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10680. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10681. }
  10682. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10683. Engine.audioEngine = new BABYLON.AudioEngine();
  10684. }
  10685. // Prepare buffer pointers
  10686. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10687. this._currentBufferPointers[i] = new BufferPointer();
  10688. }
  10689. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10690. // Load WebVR Devices
  10691. if (options.autoEnableWebVR) {
  10692. this.initWebVR();
  10693. }
  10694. // Detect if we are running on a faulty buggy OS.
  10695. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10696. // Detect if we are running on a faulty buggy desktop OS.
  10697. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10698. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10699. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10700. }
  10701. Object.defineProperty(Engine, "LastCreatedEngine", {
  10702. get: function () {
  10703. if (Engine.Instances.length === 0) {
  10704. return null;
  10705. }
  10706. return Engine.Instances[Engine.Instances.length - 1];
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "LastCreatedScene", {
  10712. get: function () {
  10713. var lastCreatedEngine = Engine.LastCreatedEngine;
  10714. if (!lastCreatedEngine) {
  10715. return null;
  10716. }
  10717. if (lastCreatedEngine.scenes.length === 0) {
  10718. return null;
  10719. }
  10720. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. /**
  10726. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10727. */
  10728. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10729. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10730. var engine = Engine.Instances[engineIndex];
  10731. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10732. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10733. }
  10734. }
  10735. };
  10736. Object.defineProperty(Engine, "NEVER", {
  10737. get: function () {
  10738. return Engine._NEVER;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(Engine, "ALWAYS", {
  10744. get: function () {
  10745. return Engine._ALWAYS;
  10746. },
  10747. enumerable: true,
  10748. configurable: true
  10749. });
  10750. Object.defineProperty(Engine, "LESS", {
  10751. get: function () {
  10752. return Engine._LESS;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(Engine, "EQUAL", {
  10758. get: function () {
  10759. return Engine._EQUAL;
  10760. },
  10761. enumerable: true,
  10762. configurable: true
  10763. });
  10764. Object.defineProperty(Engine, "LEQUAL", {
  10765. get: function () {
  10766. return Engine._LEQUAL;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(Engine, "GREATER", {
  10772. get: function () {
  10773. return Engine._GREATER;
  10774. },
  10775. enumerable: true,
  10776. configurable: true
  10777. });
  10778. Object.defineProperty(Engine, "GEQUAL", {
  10779. get: function () {
  10780. return Engine._GEQUAL;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(Engine, "NOTEQUAL", {
  10786. get: function () {
  10787. return Engine._NOTEQUAL;
  10788. },
  10789. enumerable: true,
  10790. configurable: true
  10791. });
  10792. Object.defineProperty(Engine, "KEEP", {
  10793. get: function () {
  10794. return Engine._KEEP;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(Engine, "REPLACE", {
  10800. get: function () {
  10801. return Engine._REPLACE;
  10802. },
  10803. enumerable: true,
  10804. configurable: true
  10805. });
  10806. Object.defineProperty(Engine, "INCR", {
  10807. get: function () {
  10808. return Engine._INCR;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "DECR", {
  10814. get: function () {
  10815. return Engine._DECR;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(Engine, "INVERT", {
  10821. get: function () {
  10822. return Engine._INVERT;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(Engine, "INCR_WRAP", {
  10828. get: function () {
  10829. return Engine._INCR_WRAP;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(Engine, "DECR_WRAP", {
  10835. get: function () {
  10836. return Engine._DECR_WRAP;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10842. get: function () {
  10843. return Engine._ALPHA_DISABLE;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10849. get: function () {
  10850. return Engine._ALPHA_ONEONE;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(Engine, "ALPHA_ADD", {
  10856. get: function () {
  10857. return Engine._ALPHA_ADD;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10863. get: function () {
  10864. return Engine._ALPHA_COMBINE;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10870. get: function () {
  10871. return Engine._ALPHA_SUBTRACT;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10877. get: function () {
  10878. return Engine._ALPHA_MULTIPLY;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10884. get: function () {
  10885. return Engine._ALPHA_MAXIMIZED;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10891. get: function () {
  10892. return Engine._ALPHA_PREMULTIPLIED;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10898. get: function () {
  10899. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10905. get: function () {
  10906. return Engine._ALPHA_INTERPOLATE;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10912. get: function () {
  10913. return Engine._ALPHA_SCREENMODE;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10919. get: function () {
  10920. return Engine._DELAYLOADSTATE_NONE;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10926. get: function () {
  10927. return Engine._DELAYLOADSTATE_LOADED;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10933. get: function () {
  10934. return Engine._DELAYLOADSTATE_LOADING;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10940. get: function () {
  10941. return Engine._DELAYLOADSTATE_NOTLOADED;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10947. get: function () {
  10948. return Engine._TEXTUREFORMAT_ALPHA;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10954. get: function () {
  10955. return Engine._TEXTUREFORMAT_LUMINANCE;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10961. /**
  10962. * R32F
  10963. */
  10964. get: function () {
  10965. return Engine._TEXTUREFORMAT_R32F;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10971. /**
  10972. * RG32F
  10973. */
  10974. get: function () {
  10975. return Engine._TEXTUREFORMAT_RG32F;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10981. /**
  10982. * RGB32F
  10983. */
  10984. get: function () {
  10985. return Engine._TEXTUREFORMAT_RGB32F;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10991. /**
  10992. * RGBA32F
  10993. */
  10994. get: function () {
  10995. return Engine._TEXTUREFORMAT_RGBA32F;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11001. get: function () {
  11002. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11008. get: function () {
  11009. return Engine._TEXTUREFORMAT_RGB;
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11015. get: function () {
  11016. return Engine._TEXTUREFORMAT_RGBA;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11022. get: function () {
  11023. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11024. },
  11025. enumerable: true,
  11026. configurable: true
  11027. });
  11028. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11029. get: function () {
  11030. return Engine._TEXTURETYPE_FLOAT;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11036. get: function () {
  11037. return Engine._TEXTURETYPE_HALF_FLOAT;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11043. get: function () {
  11044. return Engine._SCALEMODE_FLOOR;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11050. get: function () {
  11051. return Engine._SCALEMODE_NEAREST;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11057. get: function () {
  11058. return Engine._SCALEMODE_CEILING;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine, "Version", {
  11064. get: function () {
  11065. return "3.2.0-alphaB";
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11071. get: function () {
  11072. return this._vrExclusivePointerMode;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11078. get: function () {
  11079. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11080. },
  11081. enumerable: true,
  11082. configurable: true
  11083. });
  11084. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11085. get: function () {
  11086. return this._webGLVersion < 2 || this.forcePOTTextures;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(Engine.prototype, "badOS", {
  11092. get: function () {
  11093. return this._badOS;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11099. get: function () {
  11100. return this._badDesktopOS;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11106. get: function () {
  11107. return this._performanceMonitor;
  11108. },
  11109. enumerable: true,
  11110. configurable: true
  11111. });
  11112. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11113. get: function () {
  11114. return this._texturesSupported;
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11120. get: function () {
  11121. return this._textureFormatInUse;
  11122. },
  11123. enumerable: true,
  11124. configurable: true
  11125. });
  11126. Object.defineProperty(Engine.prototype, "currentViewport", {
  11127. get: function () {
  11128. return this._cachedViewport;
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11134. // Empty texture
  11135. get: function () {
  11136. if (!this._emptyTexture) {
  11137. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11138. }
  11139. return this._emptyTexture;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11145. get: function () {
  11146. if (!this._emptyTexture3D) {
  11147. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11148. }
  11149. return this._emptyTexture3D;
  11150. },
  11151. enumerable: true,
  11152. configurable: true
  11153. });
  11154. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11155. get: function () {
  11156. if (!this._emptyCubeTexture) {
  11157. var faceData = new Uint8Array(4);
  11158. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11159. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11160. }
  11161. return this._emptyCubeTexture;
  11162. },
  11163. enumerable: true,
  11164. configurable: true
  11165. });
  11166. Engine.prototype._rebuildInternalTextures = function () {
  11167. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11168. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11169. var internalTexture = currentState_1[_i];
  11170. internalTexture._rebuild();
  11171. }
  11172. };
  11173. Engine.prototype._rebuildEffects = function () {
  11174. for (var key in this._compiledEffects) {
  11175. var effect = this._compiledEffects[key];
  11176. effect._prepareEffect();
  11177. }
  11178. BABYLON.Effect.ResetCache();
  11179. };
  11180. Engine.prototype._rebuildBuffers = function () {
  11181. // Index / Vertex
  11182. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11183. var scene = _a[_i];
  11184. scene.resetCachedMaterial();
  11185. scene._rebuildGeometries();
  11186. scene._rebuildTextures();
  11187. }
  11188. // Uniforms
  11189. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11190. var uniformBuffer = _c[_b];
  11191. uniformBuffer._rebuild();
  11192. }
  11193. };
  11194. Engine.prototype._initGLContext = function () {
  11195. // Caps
  11196. this._caps = new EngineCapabilities();
  11197. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11198. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11199. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11200. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11201. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11202. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11203. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11204. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11205. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11206. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11207. // Infos
  11208. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11209. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11210. if (rendererInfo != null) {
  11211. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11212. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11213. }
  11214. if (!this._glVendor) {
  11215. this._glVendor = "Unknown vendor";
  11216. }
  11217. if (!this._glRenderer) {
  11218. this._glRenderer = "Unknown renderer";
  11219. }
  11220. // Constants
  11221. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11222. if (this._gl.RGBA16F !== 0x881A) {
  11223. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11224. }
  11225. if (this._gl.RGBA32F !== 0x8814) {
  11226. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11227. }
  11228. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11229. this._gl.DEPTH24_STENCIL8 = 35056;
  11230. }
  11231. // Extensions
  11232. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11233. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11234. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11235. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11236. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11237. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11238. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11239. 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');
  11240. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11241. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11242. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11243. this._caps.highPrecisionShaderSupported = true;
  11244. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11245. if (this._caps.timerQuery) {
  11246. if (this._webGLVersion === 1) {
  11247. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11248. }
  11249. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11250. }
  11251. // Checks if some of the format renders first to allow the use of webgl inspector.
  11252. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11253. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11254. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11255. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11256. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11257. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11258. if (this._webGLVersion > 1) {
  11259. this._gl.HALF_FLOAT_OES = 0x140B;
  11260. }
  11261. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11262. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11263. // Draw buffers
  11264. if (this._webGLVersion > 1) {
  11265. this._caps.drawBuffersExtension = true;
  11266. }
  11267. else {
  11268. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11269. if (drawBuffersExtension !== null) {
  11270. this._caps.drawBuffersExtension = true;
  11271. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11272. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11273. for (var i = 0; i < 16; i++) {
  11274. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11275. }
  11276. }
  11277. else {
  11278. this._caps.drawBuffersExtension = false;
  11279. }
  11280. }
  11281. // Depth Texture
  11282. if (this._webGLVersion > 1) {
  11283. this._caps.depthTextureExtension = true;
  11284. }
  11285. else {
  11286. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11287. if (depthTextureExtension != null) {
  11288. this._caps.depthTextureExtension = true;
  11289. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11290. }
  11291. }
  11292. // Vertex array object
  11293. if (this._webGLVersion > 1) {
  11294. this._caps.vertexArrayObject = true;
  11295. }
  11296. else {
  11297. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11298. if (vertexArrayObjectExtension != null) {
  11299. this._caps.vertexArrayObject = true;
  11300. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11301. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11302. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11303. }
  11304. else {
  11305. this._caps.vertexArrayObject = false;
  11306. }
  11307. }
  11308. // Instances count
  11309. if (this._webGLVersion > 1) {
  11310. this._caps.instancedArrays = true;
  11311. }
  11312. else {
  11313. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11314. if (instanceExtension != null) {
  11315. this._caps.instancedArrays = true;
  11316. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11317. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11318. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11319. }
  11320. else {
  11321. this._caps.instancedArrays = false;
  11322. }
  11323. }
  11324. // Intelligently add supported compressed formats in order to check for.
  11325. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11326. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11327. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11328. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11329. if (this._caps.astc)
  11330. this.texturesSupported.push('-astc.ktx');
  11331. if (this._caps.s3tc)
  11332. this.texturesSupported.push('-dxt.ktx');
  11333. if (this._caps.pvrtc)
  11334. this.texturesSupported.push('-pvrtc.ktx');
  11335. if (this._caps.etc2)
  11336. this.texturesSupported.push('-etc2.ktx');
  11337. if (this._caps.etc1)
  11338. this.texturesSupported.push('-etc1.ktx');
  11339. if (this._gl.getShaderPrecisionFormat) {
  11340. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11341. if (highp) {
  11342. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11343. }
  11344. }
  11345. // Depth buffer
  11346. this.setDepthBuffer(true);
  11347. this.setDepthFunctionToLessOrEqual();
  11348. this.setDepthWrite(true);
  11349. // Texture maps
  11350. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11351. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11352. this._nextFreeTextureSlots.push(slot);
  11353. }
  11354. };
  11355. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11356. get: function () {
  11357. return this._webGLVersion;
  11358. },
  11359. enumerable: true,
  11360. configurable: true
  11361. });
  11362. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11363. /**
  11364. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11365. */
  11366. get: function () {
  11367. return this._isStencilEnable;
  11368. },
  11369. enumerable: true,
  11370. configurable: true
  11371. });
  11372. Engine.prototype._prepareWorkingCanvas = function () {
  11373. if (this._workingCanvas) {
  11374. return;
  11375. }
  11376. this._workingCanvas = document.createElement("canvas");
  11377. var context = this._workingCanvas.getContext("2d");
  11378. if (context) {
  11379. this._workingContext = context;
  11380. }
  11381. };
  11382. Engine.prototype.resetTextureCache = function () {
  11383. for (var key in this._boundTexturesCache) {
  11384. var boundTexture = this._boundTexturesCache[key];
  11385. if (boundTexture) {
  11386. this._removeDesignatedSlot(boundTexture);
  11387. }
  11388. this._boundTexturesCache[key] = null;
  11389. }
  11390. if (!this.disableTextureBindingOptimization) {
  11391. this._nextFreeTextureSlots = [];
  11392. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11393. this._nextFreeTextureSlots.push(slot);
  11394. }
  11395. }
  11396. this._currentTextureChannel = -1;
  11397. };
  11398. Engine.prototype.isDeterministicLockStep = function () {
  11399. return this._deterministicLockstep;
  11400. };
  11401. Engine.prototype.getLockstepMaxSteps = function () {
  11402. return this._lockstepMaxSteps;
  11403. };
  11404. Engine.prototype.getGlInfo = function () {
  11405. return {
  11406. vendor: this._glVendor,
  11407. renderer: this._glRenderer,
  11408. version: this._glVersion
  11409. };
  11410. };
  11411. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11412. if (useScreen === void 0) { useScreen = false; }
  11413. var viewport = camera.viewport;
  11414. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11415. };
  11416. Engine.prototype.getRenderWidth = function (useScreen) {
  11417. if (useScreen === void 0) { useScreen = false; }
  11418. if (!useScreen && this._currentRenderTarget) {
  11419. return this._currentRenderTarget.width;
  11420. }
  11421. return this._gl.drawingBufferWidth;
  11422. };
  11423. Engine.prototype.getRenderHeight = function (useScreen) {
  11424. if (useScreen === void 0) { useScreen = false; }
  11425. if (!useScreen && this._currentRenderTarget) {
  11426. return this._currentRenderTarget.height;
  11427. }
  11428. return this._gl.drawingBufferHeight;
  11429. };
  11430. Engine.prototype.getRenderingCanvas = function () {
  11431. return this._renderingCanvas;
  11432. };
  11433. Engine.prototype.getRenderingCanvasClientRect = function () {
  11434. if (!this._renderingCanvas) {
  11435. return null;
  11436. }
  11437. return this._renderingCanvas.getBoundingClientRect();
  11438. };
  11439. Engine.prototype.setHardwareScalingLevel = function (level) {
  11440. this._hardwareScalingLevel = level;
  11441. this.resize();
  11442. };
  11443. Engine.prototype.getHardwareScalingLevel = function () {
  11444. return this._hardwareScalingLevel;
  11445. };
  11446. Engine.prototype.getLoadedTexturesCache = function () {
  11447. return this._internalTexturesCache;
  11448. };
  11449. Engine.prototype.getCaps = function () {
  11450. return this._caps;
  11451. };
  11452. Object.defineProperty(Engine.prototype, "drawCalls", {
  11453. /** The number of draw calls submitted last frame */
  11454. get: function () {
  11455. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11456. return 0;
  11457. },
  11458. enumerable: true,
  11459. configurable: true
  11460. });
  11461. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11462. get: function () {
  11463. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11464. return null;
  11465. },
  11466. enumerable: true,
  11467. configurable: true
  11468. });
  11469. Engine.prototype.getDepthFunction = function () {
  11470. return this._depthCullingState.depthFunc;
  11471. };
  11472. Engine.prototype.setDepthFunction = function (depthFunc) {
  11473. this._depthCullingState.depthFunc = depthFunc;
  11474. };
  11475. Engine.prototype.setDepthFunctionToGreater = function () {
  11476. this._depthCullingState.depthFunc = this._gl.GREATER;
  11477. };
  11478. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11479. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11480. };
  11481. Engine.prototype.setDepthFunctionToLess = function () {
  11482. this._depthCullingState.depthFunc = this._gl.LESS;
  11483. };
  11484. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11485. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11486. };
  11487. Engine.prototype.getStencilBuffer = function () {
  11488. return this._stencilState.stencilTest;
  11489. };
  11490. Engine.prototype.setStencilBuffer = function (enable) {
  11491. this._stencilState.stencilTest = enable;
  11492. };
  11493. Engine.prototype.getStencilMask = function () {
  11494. return this._stencilState.stencilMask;
  11495. };
  11496. Engine.prototype.setStencilMask = function (mask) {
  11497. this._stencilState.stencilMask = mask;
  11498. };
  11499. Engine.prototype.getStencilFunction = function () {
  11500. return this._stencilState.stencilFunc;
  11501. };
  11502. Engine.prototype.getStencilFunctionReference = function () {
  11503. return this._stencilState.stencilFuncRef;
  11504. };
  11505. Engine.prototype.getStencilFunctionMask = function () {
  11506. return this._stencilState.stencilFuncMask;
  11507. };
  11508. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11509. this._stencilState.stencilFunc = stencilFunc;
  11510. };
  11511. Engine.prototype.setStencilFunctionReference = function (reference) {
  11512. this._stencilState.stencilFuncRef = reference;
  11513. };
  11514. Engine.prototype.setStencilFunctionMask = function (mask) {
  11515. this._stencilState.stencilFuncMask = mask;
  11516. };
  11517. Engine.prototype.getStencilOperationFail = function () {
  11518. return this._stencilState.stencilOpStencilFail;
  11519. };
  11520. Engine.prototype.getStencilOperationDepthFail = function () {
  11521. return this._stencilState.stencilOpDepthFail;
  11522. };
  11523. Engine.prototype.getStencilOperationPass = function () {
  11524. return this._stencilState.stencilOpStencilDepthPass;
  11525. };
  11526. Engine.prototype.setStencilOperationFail = function (operation) {
  11527. this._stencilState.stencilOpStencilFail = operation;
  11528. };
  11529. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11530. this._stencilState.stencilOpDepthFail = operation;
  11531. };
  11532. Engine.prototype.setStencilOperationPass = function (operation) {
  11533. this._stencilState.stencilOpStencilDepthPass = operation;
  11534. };
  11535. Engine.prototype.setDitheringState = function (value) {
  11536. if (value) {
  11537. this._gl.enable(this._gl.DITHER);
  11538. }
  11539. else {
  11540. this._gl.disable(this._gl.DITHER);
  11541. }
  11542. };
  11543. Engine.prototype.setRasterizerState = function (value) {
  11544. if (value) {
  11545. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11546. }
  11547. else {
  11548. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11549. }
  11550. };
  11551. /**
  11552. * stop executing a render loop function and remove it from the execution array
  11553. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11554. */
  11555. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11556. if (!renderFunction) {
  11557. this._activeRenderLoops = [];
  11558. return;
  11559. }
  11560. var index = this._activeRenderLoops.indexOf(renderFunction);
  11561. if (index >= 0) {
  11562. this._activeRenderLoops.splice(index, 1);
  11563. }
  11564. };
  11565. Engine.prototype._renderLoop = function () {
  11566. if (!this._contextWasLost) {
  11567. var shouldRender = true;
  11568. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11569. shouldRender = false;
  11570. }
  11571. if (shouldRender) {
  11572. // Start new frame
  11573. this.beginFrame();
  11574. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11575. var renderFunction = this._activeRenderLoops[index];
  11576. renderFunction();
  11577. }
  11578. // Present
  11579. this.endFrame();
  11580. }
  11581. }
  11582. if (this._activeRenderLoops.length > 0) {
  11583. // Register new frame
  11584. var requester = null;
  11585. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11586. requester = this._vrDisplay;
  11587. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11588. }
  11589. else {
  11590. this._renderingQueueLaunched = false;
  11591. }
  11592. };
  11593. /**
  11594. * Register and execute a render loop. The engine can have more than one render function.
  11595. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11596. * @example
  11597. * engine.runRenderLoop(function () {
  11598. * scene.render()
  11599. * })
  11600. */
  11601. Engine.prototype.runRenderLoop = function (renderFunction) {
  11602. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11603. return;
  11604. }
  11605. this._activeRenderLoops.push(renderFunction);
  11606. if (!this._renderingQueueLaunched) {
  11607. this._renderingQueueLaunched = true;
  11608. this._bindedRenderFunction = this._renderLoop.bind(this);
  11609. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11610. }
  11611. };
  11612. /**
  11613. * Toggle full screen mode.
  11614. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11615. * @param {any} options - an options object to be sent to the requestFullscreen function
  11616. */
  11617. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11618. if (this.isFullscreen) {
  11619. BABYLON.Tools.ExitFullscreen();
  11620. }
  11621. else {
  11622. this._pointerLockRequested = requestPointerLock;
  11623. if (this._renderingCanvas) {
  11624. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11625. }
  11626. }
  11627. };
  11628. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11629. if (stencil === void 0) { stencil = false; }
  11630. this.applyStates();
  11631. var mode = 0;
  11632. if (backBuffer && color) {
  11633. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11634. mode |= this._gl.COLOR_BUFFER_BIT;
  11635. }
  11636. if (depth) {
  11637. this._gl.clearDepth(1.0);
  11638. mode |= this._gl.DEPTH_BUFFER_BIT;
  11639. }
  11640. if (stencil) {
  11641. this._gl.clearStencil(0);
  11642. mode |= this._gl.STENCIL_BUFFER_BIT;
  11643. }
  11644. this._gl.clear(mode);
  11645. };
  11646. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11647. var gl = this._gl;
  11648. // Save state
  11649. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11650. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11651. // Change state
  11652. gl.enable(gl.SCISSOR_TEST);
  11653. gl.scissor(x, y, width, height);
  11654. // Clear
  11655. this.clear(clearColor, true, true, true);
  11656. // Restore state
  11657. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11658. if (curScissor === true) {
  11659. gl.enable(gl.SCISSOR_TEST);
  11660. }
  11661. else {
  11662. gl.disable(gl.SCISSOR_TEST);
  11663. }
  11664. };
  11665. /**
  11666. * Set the WebGL's viewport
  11667. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11668. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11669. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11670. */
  11671. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11672. var width = requiredWidth || this.getRenderWidth();
  11673. var height = requiredHeight || this.getRenderHeight();
  11674. var x = viewport.x || 0;
  11675. var y = viewport.y || 0;
  11676. this._cachedViewport = viewport;
  11677. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11678. };
  11679. /**
  11680. * Directly set the WebGL Viewport
  11681. * The x, y, width & height are directly passed to the WebGL call
  11682. * @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.
  11683. */
  11684. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11685. var currentViewport = this._cachedViewport;
  11686. this._cachedViewport = null;
  11687. this._gl.viewport(x, y, width, height);
  11688. return currentViewport;
  11689. };
  11690. Engine.prototype.beginFrame = function () {
  11691. this.onBeginFrameObservable.notifyObservers(this);
  11692. this._measureFps();
  11693. };
  11694. Engine.prototype.endFrame = function () {
  11695. //force a flush in case we are using a bad OS.
  11696. if (this._badOS) {
  11697. this.flushFramebuffer();
  11698. }
  11699. //submit frame to the vr device, if enabled
  11700. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11701. // TODO: We should only submit the frame if we read frameData successfully.
  11702. this._vrDisplay.submitFrame();
  11703. }
  11704. this.onEndFrameObservable.notifyObservers(this);
  11705. };
  11706. /**
  11707. * resize the view according to the canvas' size.
  11708. * @example
  11709. * window.addEventListener("resize", function () {
  11710. * engine.resize();
  11711. * });
  11712. */
  11713. Engine.prototype.resize = function () {
  11714. // We're not resizing the size of the canvas while in VR mode & presenting
  11715. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11716. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11717. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11718. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11719. }
  11720. };
  11721. /**
  11722. * force a specific size of the canvas
  11723. * @param {number} width - the new canvas' width
  11724. * @param {number} height - the new canvas' height
  11725. */
  11726. Engine.prototype.setSize = function (width, height) {
  11727. if (!this._renderingCanvas) {
  11728. return;
  11729. }
  11730. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11731. return;
  11732. }
  11733. this._renderingCanvas.width = width;
  11734. this._renderingCanvas.height = height;
  11735. for (var index = 0; index < this.scenes.length; index++) {
  11736. var scene = this.scenes[index];
  11737. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11738. var cam = scene.cameras[camIndex];
  11739. cam._currentRenderId = 0;
  11740. }
  11741. }
  11742. if (this.onResizeObservable.hasObservers) {
  11743. this.onResizeObservable.notifyObservers(this);
  11744. }
  11745. };
  11746. // WebVR functions
  11747. Engine.prototype.isVRDevicePresent = function () {
  11748. return !!this._vrDisplay;
  11749. };
  11750. Engine.prototype.getVRDevice = function () {
  11751. return this._vrDisplay;
  11752. };
  11753. /**
  11754. * Initializes a webVR display and starts listening to display change events.
  11755. * The onVRDisplayChangedObservable will be notified upon these changes.
  11756. * @returns The onVRDisplayChangedObservable.
  11757. */
  11758. Engine.prototype.initWebVR = function () {
  11759. this.initWebVRAsync();
  11760. return this.onVRDisplayChangedObservable;
  11761. };
  11762. /**
  11763. * Initializes a webVR display and starts listening to display change events.
  11764. * The onVRDisplayChangedObservable will be notified upon these changes.
  11765. * @returns A promise containing a VRDisplay and if vr is supported.
  11766. */
  11767. Engine.prototype.initWebVRAsync = function () {
  11768. var _this = this;
  11769. var notifyObservers = function () {
  11770. var eventArgs = {
  11771. vrDisplay: _this._vrDisplay,
  11772. vrSupported: _this._vrSupported
  11773. };
  11774. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11775. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11776. };
  11777. if (!this._onVrDisplayConnect) {
  11778. this._onVrDisplayConnect = function (event) {
  11779. _this._vrDisplay = event.display;
  11780. notifyObservers();
  11781. };
  11782. this._onVrDisplayDisconnect = function () {
  11783. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11784. _this._vrDisplay = undefined;
  11785. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11786. notifyObservers();
  11787. };
  11788. this._onVrDisplayPresentChange = function () {
  11789. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11790. };
  11791. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11792. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11793. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11794. }
  11795. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11796. this._webVRInitPromise.then(notifyObservers);
  11797. return this._webVRInitPromise;
  11798. };
  11799. Engine.prototype.enableVR = function () {
  11800. var _this = this;
  11801. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11802. var onResolved = function () {
  11803. _this.onVRRequestPresentComplete.notifyObservers(true);
  11804. _this._onVRFullScreenTriggered();
  11805. };
  11806. var onRejected = function () {
  11807. _this.onVRRequestPresentComplete.notifyObservers(false);
  11808. };
  11809. this.onVRRequestPresentStart.notifyObservers(this);
  11810. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11811. }
  11812. };
  11813. Engine.prototype.disableVR = function () {
  11814. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11815. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11816. }
  11817. };
  11818. Engine.prototype._getVRDisplaysAsync = function () {
  11819. var _this = this;
  11820. return new Promise(function (res, rej) {
  11821. if (navigator.getVRDisplays) {
  11822. navigator.getVRDisplays().then(function (devices) {
  11823. _this._vrSupported = true;
  11824. // note that devices may actually be an empty array. This is fine;
  11825. // we expect this._vrDisplay to be undefined in this case.
  11826. _this._vrDisplay = devices[0];
  11827. res({
  11828. vrDisplay: _this._vrDisplay,
  11829. vrSupported: _this._vrSupported
  11830. });
  11831. });
  11832. }
  11833. else {
  11834. _this._vrDisplay = undefined;
  11835. _this._vrSupported = false;
  11836. res({
  11837. vrDisplay: _this._vrDisplay,
  11838. vrSupported: _this._vrSupported
  11839. });
  11840. }
  11841. });
  11842. };
  11843. /**
  11844. * Binds the frame buffer to the specified texture.
  11845. * @param texture The texture to render to or null for the default canvas
  11846. * @param faceIndex The face of the texture to render to in case of cube texture
  11847. * @param requiredWidth The width of the target to render to
  11848. * @param requiredHeight The height of the target to render to
  11849. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11850. * @param depthStencilTexture The depth stencil texture to use to render
  11851. */
  11852. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11853. if (this._currentRenderTarget) {
  11854. this.unBindFramebuffer(this._currentRenderTarget);
  11855. }
  11856. this._currentRenderTarget = texture;
  11857. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11858. var gl = this._gl;
  11859. if (texture.isCube) {
  11860. if (faceIndex === undefined) {
  11861. faceIndex = 0;
  11862. }
  11863. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11864. if (depthStencilTexture) {
  11865. if (depthStencilTexture._generateStencilBuffer) {
  11866. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11867. }
  11868. else {
  11869. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11870. }
  11871. }
  11872. }
  11873. if (this._cachedViewport && !forceFullscreenViewport) {
  11874. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11875. }
  11876. else {
  11877. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11878. }
  11879. this.wipeCaches();
  11880. };
  11881. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11882. if (this._currentFramebuffer !== framebuffer) {
  11883. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11884. this._currentFramebuffer = framebuffer;
  11885. }
  11886. };
  11887. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11888. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11889. this._currentRenderTarget = null;
  11890. // If MSAA, we need to bitblt back to main texture
  11891. var gl = this._gl;
  11892. if (texture._MSAAFramebuffer) {
  11893. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11894. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11895. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11896. }
  11897. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11898. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11899. gl.generateMipmap(gl.TEXTURE_2D);
  11900. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11901. }
  11902. if (onBeforeUnbind) {
  11903. if (texture._MSAAFramebuffer) {
  11904. // Bind the correct framebuffer
  11905. this.bindUnboundFramebuffer(texture._framebuffer);
  11906. }
  11907. onBeforeUnbind();
  11908. }
  11909. this.bindUnboundFramebuffer(null);
  11910. };
  11911. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11912. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11913. this._currentRenderTarget = null;
  11914. // If MSAA, we need to bitblt back to main texture
  11915. var gl = this._gl;
  11916. if (textures[0]._MSAAFramebuffer) {
  11917. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11918. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11919. var attachments = textures[0]._attachments;
  11920. if (!attachments) {
  11921. attachments = new Array(textures.length);
  11922. textures[0]._attachments = attachments;
  11923. }
  11924. for (var i = 0; i < textures.length; i++) {
  11925. var texture = textures[i];
  11926. for (var j = 0; j < attachments.length; j++) {
  11927. attachments[j] = gl.NONE;
  11928. }
  11929. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11930. gl.readBuffer(attachments[i]);
  11931. gl.drawBuffers(attachments);
  11932. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11933. }
  11934. for (var i = 0; i < attachments.length; i++) {
  11935. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11936. }
  11937. gl.drawBuffers(attachments);
  11938. }
  11939. for (var i = 0; i < textures.length; i++) {
  11940. var texture = textures[i];
  11941. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11942. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11943. gl.generateMipmap(gl.TEXTURE_2D);
  11944. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11945. }
  11946. }
  11947. if (onBeforeUnbind) {
  11948. if (textures[0]._MSAAFramebuffer) {
  11949. // Bind the correct framebuffer
  11950. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11951. }
  11952. onBeforeUnbind();
  11953. }
  11954. this.bindUnboundFramebuffer(null);
  11955. };
  11956. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11957. if (texture.generateMipMaps) {
  11958. var gl = this._gl;
  11959. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11960. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11961. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11962. }
  11963. };
  11964. Engine.prototype.flushFramebuffer = function () {
  11965. this._gl.flush();
  11966. };
  11967. Engine.prototype.restoreDefaultFramebuffer = function () {
  11968. if (this._currentRenderTarget) {
  11969. this.unBindFramebuffer(this._currentRenderTarget);
  11970. }
  11971. else {
  11972. this.bindUnboundFramebuffer(null);
  11973. }
  11974. if (this._cachedViewport) {
  11975. this.setViewport(this._cachedViewport);
  11976. }
  11977. this.wipeCaches();
  11978. };
  11979. // UBOs
  11980. Engine.prototype.createUniformBuffer = function (elements) {
  11981. var ubo = this._gl.createBuffer();
  11982. if (!ubo) {
  11983. throw new Error("Unable to create uniform buffer");
  11984. }
  11985. this.bindUniformBuffer(ubo);
  11986. if (elements instanceof Float32Array) {
  11987. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11988. }
  11989. else {
  11990. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11991. }
  11992. this.bindUniformBuffer(null);
  11993. ubo.references = 1;
  11994. return ubo;
  11995. };
  11996. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11997. var ubo = this._gl.createBuffer();
  11998. if (!ubo) {
  11999. throw new Error("Unable to create dynamic uniform buffer");
  12000. }
  12001. this.bindUniformBuffer(ubo);
  12002. if (elements instanceof Float32Array) {
  12003. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12004. }
  12005. else {
  12006. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12007. }
  12008. this.bindUniformBuffer(null);
  12009. ubo.references = 1;
  12010. return ubo;
  12011. };
  12012. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12013. this.bindUniformBuffer(uniformBuffer);
  12014. if (offset === undefined) {
  12015. offset = 0;
  12016. }
  12017. if (count === undefined) {
  12018. if (elements instanceof Float32Array) {
  12019. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12020. }
  12021. else {
  12022. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12023. }
  12024. }
  12025. else {
  12026. if (elements instanceof Float32Array) {
  12027. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12028. }
  12029. else {
  12030. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12031. }
  12032. }
  12033. this.bindUniformBuffer(null);
  12034. };
  12035. // VBOs
  12036. Engine.prototype._resetVertexBufferBinding = function () {
  12037. this.bindArrayBuffer(null);
  12038. this._cachedVertexBuffers = null;
  12039. };
  12040. Engine.prototype.createVertexBuffer = function (vertices) {
  12041. var vbo = this._gl.createBuffer();
  12042. if (!vbo) {
  12043. throw new Error("Unable to create vertex buffer");
  12044. }
  12045. this.bindArrayBuffer(vbo);
  12046. if (vertices instanceof Float32Array) {
  12047. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12048. }
  12049. else {
  12050. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12051. }
  12052. this._resetVertexBufferBinding();
  12053. vbo.references = 1;
  12054. return vbo;
  12055. };
  12056. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12057. var vbo = this._gl.createBuffer();
  12058. if (!vbo) {
  12059. throw new Error("Unable to create dynamic vertex buffer");
  12060. }
  12061. this.bindArrayBuffer(vbo);
  12062. if (vertices instanceof Float32Array) {
  12063. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12064. }
  12065. else {
  12066. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12067. }
  12068. this._resetVertexBufferBinding();
  12069. vbo.references = 1;
  12070. return vbo;
  12071. };
  12072. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12073. if (offset === void 0) { offset = 0; }
  12074. // Force cache update
  12075. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12076. this.bindIndexBuffer(indexBuffer);
  12077. var arrayBuffer;
  12078. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12079. arrayBuffer = indices;
  12080. }
  12081. else {
  12082. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12083. }
  12084. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12085. this._resetIndexBufferBinding();
  12086. };
  12087. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12088. this.bindArrayBuffer(vertexBuffer);
  12089. if (offset === undefined) {
  12090. offset = 0;
  12091. }
  12092. if (count === undefined) {
  12093. if (vertices instanceof Float32Array) {
  12094. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12095. }
  12096. else {
  12097. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12098. }
  12099. }
  12100. else {
  12101. if (vertices instanceof Float32Array) {
  12102. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12103. }
  12104. else {
  12105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12106. }
  12107. }
  12108. this._resetVertexBufferBinding();
  12109. };
  12110. Engine.prototype._resetIndexBufferBinding = function () {
  12111. this.bindIndexBuffer(null);
  12112. this._cachedIndexBuffer = null;
  12113. };
  12114. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12115. var vbo = this._gl.createBuffer();
  12116. if (!vbo) {
  12117. throw new Error("Unable to create index buffer");
  12118. }
  12119. this.bindIndexBuffer(vbo);
  12120. // Check for 32 bits indices
  12121. var arrayBuffer;
  12122. var need32Bits = false;
  12123. if (indices instanceof Uint16Array) {
  12124. arrayBuffer = indices;
  12125. }
  12126. else {
  12127. //check 32 bit support
  12128. if (this._caps.uintIndices) {
  12129. if (indices instanceof Uint32Array) {
  12130. arrayBuffer = indices;
  12131. need32Bits = true;
  12132. }
  12133. else {
  12134. //number[] or Int32Array, check if 32 bit is necessary
  12135. for (var index = 0; index < indices.length; index++) {
  12136. if (indices[index] > 65535) {
  12137. need32Bits = true;
  12138. break;
  12139. }
  12140. }
  12141. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12142. }
  12143. }
  12144. else {
  12145. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12146. arrayBuffer = new Uint16Array(indices);
  12147. }
  12148. }
  12149. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12150. this._resetIndexBufferBinding();
  12151. vbo.references = 1;
  12152. vbo.is32Bits = need32Bits;
  12153. return vbo;
  12154. };
  12155. Engine.prototype.bindArrayBuffer = function (buffer) {
  12156. if (!this._vaoRecordInProgress) {
  12157. this._unbindVertexArrayObject();
  12158. }
  12159. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12160. };
  12161. Engine.prototype.bindUniformBuffer = function (buffer) {
  12162. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12163. };
  12164. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12165. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12166. };
  12167. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12168. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12169. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12170. };
  12171. ;
  12172. Engine.prototype.bindIndexBuffer = function (buffer) {
  12173. if (!this._vaoRecordInProgress) {
  12174. this._unbindVertexArrayObject();
  12175. }
  12176. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12177. };
  12178. Engine.prototype.bindBuffer = function (buffer, target) {
  12179. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12180. this._gl.bindBuffer(target, buffer);
  12181. this._currentBoundBuffer[target] = buffer;
  12182. }
  12183. };
  12184. Engine.prototype.updateArrayBuffer = function (data) {
  12185. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12186. };
  12187. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12188. var pointer = this._currentBufferPointers[indx];
  12189. var changed = false;
  12190. if (!pointer.active) {
  12191. changed = true;
  12192. pointer.active = true;
  12193. pointer.index = indx;
  12194. pointer.size = size;
  12195. pointer.type = type;
  12196. pointer.normalized = normalized;
  12197. pointer.stride = stride;
  12198. pointer.offset = offset;
  12199. pointer.buffer = buffer;
  12200. }
  12201. else {
  12202. if (pointer.buffer !== buffer) {
  12203. pointer.buffer = buffer;
  12204. changed = true;
  12205. }
  12206. if (pointer.size !== size) {
  12207. pointer.size = size;
  12208. changed = true;
  12209. }
  12210. if (pointer.type !== type) {
  12211. pointer.type = type;
  12212. changed = true;
  12213. }
  12214. if (pointer.normalized !== normalized) {
  12215. pointer.normalized = normalized;
  12216. changed = true;
  12217. }
  12218. if (pointer.stride !== stride) {
  12219. pointer.stride = stride;
  12220. changed = true;
  12221. }
  12222. if (pointer.offset !== offset) {
  12223. pointer.offset = offset;
  12224. changed = true;
  12225. }
  12226. }
  12227. if (changed || this._vaoRecordInProgress) {
  12228. this.bindArrayBuffer(buffer);
  12229. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12230. }
  12231. };
  12232. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12233. if (indexBuffer == null) {
  12234. return;
  12235. }
  12236. if (this._cachedIndexBuffer !== indexBuffer) {
  12237. this._cachedIndexBuffer = indexBuffer;
  12238. this.bindIndexBuffer(indexBuffer);
  12239. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12240. }
  12241. };
  12242. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12243. var attributes = effect.getAttributesNames();
  12244. if (!this._vaoRecordInProgress) {
  12245. this._unbindVertexArrayObject();
  12246. }
  12247. this.unbindAllAttributes();
  12248. for (var index = 0; index < attributes.length; index++) {
  12249. var order = effect.getAttributeLocation(index);
  12250. if (order >= 0) {
  12251. var vertexBuffer = vertexBuffers[attributes[index]];
  12252. if (!vertexBuffer) {
  12253. continue;
  12254. }
  12255. this._gl.enableVertexAttribArray(order);
  12256. if (!this._vaoRecordInProgress) {
  12257. this._vertexAttribArraysEnabled[order] = true;
  12258. }
  12259. var buffer = vertexBuffer.getBuffer();
  12260. if (buffer) {
  12261. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12262. if (vertexBuffer.getIsInstanced()) {
  12263. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12264. if (!this._vaoRecordInProgress) {
  12265. this._currentInstanceLocations.push(order);
  12266. this._currentInstanceBuffers.push(buffer);
  12267. }
  12268. }
  12269. }
  12270. }
  12271. }
  12272. };
  12273. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12274. var vao = this._gl.createVertexArray();
  12275. this._vaoRecordInProgress = true;
  12276. this._gl.bindVertexArray(vao);
  12277. this._mustWipeVertexAttributes = true;
  12278. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12279. this.bindIndexBuffer(indexBuffer);
  12280. this._vaoRecordInProgress = false;
  12281. this._gl.bindVertexArray(null);
  12282. return vao;
  12283. };
  12284. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12285. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12286. this._cachedVertexArrayObject = vertexArrayObject;
  12287. this._gl.bindVertexArray(vertexArrayObject);
  12288. this._cachedVertexBuffers = null;
  12289. this._cachedIndexBuffer = null;
  12290. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12291. this._mustWipeVertexAttributes = true;
  12292. }
  12293. };
  12294. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12295. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12296. this._cachedVertexBuffers = vertexBuffer;
  12297. this._cachedEffectForVertexBuffers = effect;
  12298. var attributesCount = effect.getAttributesCount();
  12299. this._unbindVertexArrayObject();
  12300. this.unbindAllAttributes();
  12301. var offset = 0;
  12302. for (var index = 0; index < attributesCount; index++) {
  12303. if (index < vertexDeclaration.length) {
  12304. var order = effect.getAttributeLocation(index);
  12305. if (order >= 0) {
  12306. this._gl.enableVertexAttribArray(order);
  12307. this._vertexAttribArraysEnabled[order] = true;
  12308. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12309. }
  12310. offset += vertexDeclaration[index] * 4;
  12311. }
  12312. }
  12313. }
  12314. this._bindIndexBufferWithCache(indexBuffer);
  12315. };
  12316. Engine.prototype._unbindVertexArrayObject = function () {
  12317. if (!this._cachedVertexArrayObject) {
  12318. return;
  12319. }
  12320. this._cachedVertexArrayObject = null;
  12321. this._gl.bindVertexArray(null);
  12322. };
  12323. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12324. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12325. this._cachedVertexBuffers = vertexBuffers;
  12326. this._cachedEffectForVertexBuffers = effect;
  12327. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12328. }
  12329. this._bindIndexBufferWithCache(indexBuffer);
  12330. };
  12331. Engine.prototype.unbindInstanceAttributes = function () {
  12332. var boundBuffer;
  12333. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12334. var instancesBuffer = this._currentInstanceBuffers[i];
  12335. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12336. boundBuffer = instancesBuffer;
  12337. this.bindArrayBuffer(instancesBuffer);
  12338. }
  12339. var offsetLocation = this._currentInstanceLocations[i];
  12340. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12341. }
  12342. this._currentInstanceBuffers.length = 0;
  12343. this._currentInstanceLocations.length = 0;
  12344. };
  12345. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12346. this._gl.deleteVertexArray(vao);
  12347. };
  12348. Engine.prototype._releaseBuffer = function (buffer) {
  12349. buffer.references--;
  12350. if (buffer.references === 0) {
  12351. this._gl.deleteBuffer(buffer);
  12352. return true;
  12353. }
  12354. return false;
  12355. };
  12356. Engine.prototype.createInstancesBuffer = function (capacity) {
  12357. var buffer = this._gl.createBuffer();
  12358. if (!buffer) {
  12359. throw new Error("Unable to create instance buffer");
  12360. }
  12361. buffer.capacity = capacity;
  12362. this.bindArrayBuffer(buffer);
  12363. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12364. return buffer;
  12365. };
  12366. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12367. this._gl.deleteBuffer(buffer);
  12368. };
  12369. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12370. this.bindArrayBuffer(instancesBuffer);
  12371. if (data) {
  12372. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12373. }
  12374. if (offsetLocations[0].index !== undefined) {
  12375. var stride = 0;
  12376. for (var i = 0; i < offsetLocations.length; i++) {
  12377. var ai = offsetLocations[i];
  12378. stride += ai.attributeSize * 4;
  12379. }
  12380. for (var i = 0; i < offsetLocations.length; i++) {
  12381. var ai = offsetLocations[i];
  12382. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12383. this._gl.enableVertexAttribArray(ai.index);
  12384. this._vertexAttribArraysEnabled[ai.index] = true;
  12385. }
  12386. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12387. this._gl.vertexAttribDivisor(ai.index, 1);
  12388. this._currentInstanceLocations.push(ai.index);
  12389. this._currentInstanceBuffers.push(instancesBuffer);
  12390. }
  12391. }
  12392. else {
  12393. for (var index = 0; index < 4; index++) {
  12394. var offsetLocation = offsetLocations[index];
  12395. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12396. this._gl.enableVertexAttribArray(offsetLocation);
  12397. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12398. }
  12399. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12400. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12401. this._currentInstanceLocations.push(offsetLocation);
  12402. this._currentInstanceBuffers.push(instancesBuffer);
  12403. }
  12404. }
  12405. };
  12406. Engine.prototype.applyStates = function () {
  12407. this._depthCullingState.apply(this._gl);
  12408. this._stencilState.apply(this._gl);
  12409. this._alphaState.apply(this._gl);
  12410. };
  12411. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12412. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12413. };
  12414. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12415. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12416. };
  12417. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12418. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12419. };
  12420. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12421. // Apply states
  12422. this.applyStates();
  12423. this._drawCalls.addCount(1, false);
  12424. // Render
  12425. var drawMode = this.DrawMode(fillMode);
  12426. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12427. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12428. if (instancesCount) {
  12429. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12430. }
  12431. else {
  12432. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12433. }
  12434. };
  12435. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12436. // Apply states
  12437. this.applyStates();
  12438. this._drawCalls.addCount(1, false);
  12439. var drawMode = this.DrawMode(fillMode);
  12440. if (instancesCount) {
  12441. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12442. }
  12443. else {
  12444. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12445. }
  12446. };
  12447. Engine.prototype.DrawMode = function (fillMode) {
  12448. switch (fillMode) {
  12449. // Triangle views
  12450. case BABYLON.Material.TriangleFillMode:
  12451. return this._gl.TRIANGLES;
  12452. case BABYLON.Material.PointFillMode:
  12453. return this._gl.POINTS;
  12454. case BABYLON.Material.WireFrameFillMode:
  12455. return this._gl.LINES;
  12456. // Draw modes
  12457. case BABYLON.Material.PointListDrawMode:
  12458. return this._gl.POINTS;
  12459. case BABYLON.Material.LineListDrawMode:
  12460. return this._gl.LINES;
  12461. case BABYLON.Material.LineLoopDrawMode:
  12462. return this._gl.LINE_LOOP;
  12463. case BABYLON.Material.LineStripDrawMode:
  12464. return this._gl.LINE_STRIP;
  12465. case BABYLON.Material.TriangleStripDrawMode:
  12466. return this._gl.TRIANGLE_STRIP;
  12467. case BABYLON.Material.TriangleFanDrawMode:
  12468. return this._gl.TRIANGLE_FAN;
  12469. default:
  12470. return this._gl.TRIANGLES;
  12471. }
  12472. };
  12473. // Shaders
  12474. Engine.prototype._releaseEffect = function (effect) {
  12475. if (this._compiledEffects[effect._key]) {
  12476. delete this._compiledEffects[effect._key];
  12477. this._deleteProgram(effect.getProgram());
  12478. }
  12479. };
  12480. Engine.prototype._deleteProgram = function (program) {
  12481. if (program) {
  12482. program.__SPECTOR_rebuildProgram = null;
  12483. if (program.transformFeedback) {
  12484. this.deleteTransformFeedback(program.transformFeedback);
  12485. program.transformFeedback = null;
  12486. }
  12487. this._gl.deleteProgram(program);
  12488. }
  12489. };
  12490. /**
  12491. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12492. * @param samplers An array of string used to represent textures
  12493. */
  12494. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12495. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12496. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12497. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12498. if (this._compiledEffects[name]) {
  12499. var compiledEffect = this._compiledEffects[name];
  12500. if (onCompiled && compiledEffect.isReady()) {
  12501. onCompiled(compiledEffect);
  12502. }
  12503. return compiledEffect;
  12504. }
  12505. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12506. effect._key = name;
  12507. this._compiledEffects[name] = effect;
  12508. return effect;
  12509. };
  12510. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12511. if (uniformsNames === void 0) { uniformsNames = []; }
  12512. if (samplers === void 0) { samplers = []; }
  12513. if (defines === void 0) { defines = ""; }
  12514. return this.createEffect({
  12515. vertex: "particles",
  12516. fragmentElement: fragmentName
  12517. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12518. };
  12519. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12520. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12521. context = context || this._gl;
  12522. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12523. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12524. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12525. };
  12526. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12527. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12528. context = context || this._gl;
  12529. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12530. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12531. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12532. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12533. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12534. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12535. return program;
  12536. };
  12537. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12538. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12539. var shaderProgram = context.createProgram();
  12540. if (!shaderProgram) {
  12541. throw new Error("Unable to create program");
  12542. }
  12543. context.attachShader(shaderProgram, vertexShader);
  12544. context.attachShader(shaderProgram, fragmentShader);
  12545. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12546. var transformFeedback = this.createTransformFeedback();
  12547. this.bindTransformFeedback(transformFeedback);
  12548. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12549. shaderProgram.transformFeedback = transformFeedback;
  12550. }
  12551. context.linkProgram(shaderProgram);
  12552. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12553. this.bindTransformFeedback(null);
  12554. }
  12555. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12556. if (!linked) {
  12557. context.validateProgram(shaderProgram);
  12558. var error = context.getProgramInfoLog(shaderProgram);
  12559. if (error) {
  12560. throw new Error(error);
  12561. }
  12562. }
  12563. context.deleteShader(vertexShader);
  12564. context.deleteShader(fragmentShader);
  12565. return shaderProgram;
  12566. };
  12567. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12568. var results = new Array();
  12569. for (var index = 0; index < uniformsNames.length; index++) {
  12570. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12571. }
  12572. return results;
  12573. };
  12574. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12575. var results = [];
  12576. for (var index = 0; index < attributesNames.length; index++) {
  12577. try {
  12578. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12579. }
  12580. catch (e) {
  12581. results.push(-1);
  12582. }
  12583. }
  12584. return results;
  12585. };
  12586. Engine.prototype.enableEffect = function (effect) {
  12587. if (!effect) {
  12588. return;
  12589. }
  12590. // Use program
  12591. this.bindSamplers(effect);
  12592. this._currentEffect = effect;
  12593. if (effect.onBind) {
  12594. effect.onBind(effect);
  12595. }
  12596. effect.onBindObservable.notifyObservers(effect);
  12597. };
  12598. Engine.prototype.setIntArray = function (uniform, array) {
  12599. if (!uniform)
  12600. return;
  12601. this._gl.uniform1iv(uniform, array);
  12602. };
  12603. Engine.prototype.setIntArray2 = function (uniform, array) {
  12604. if (!uniform || array.length % 2 !== 0)
  12605. return;
  12606. this._gl.uniform2iv(uniform, array);
  12607. };
  12608. Engine.prototype.setIntArray3 = function (uniform, array) {
  12609. if (!uniform || array.length % 3 !== 0)
  12610. return;
  12611. this._gl.uniform3iv(uniform, array);
  12612. };
  12613. Engine.prototype.setIntArray4 = function (uniform, array) {
  12614. if (!uniform || array.length % 4 !== 0)
  12615. return;
  12616. this._gl.uniform4iv(uniform, array);
  12617. };
  12618. Engine.prototype.setFloatArray = function (uniform, array) {
  12619. if (!uniform)
  12620. return;
  12621. this._gl.uniform1fv(uniform, array);
  12622. };
  12623. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12624. if (!uniform || array.length % 2 !== 0)
  12625. return;
  12626. this._gl.uniform2fv(uniform, array);
  12627. };
  12628. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12629. if (!uniform || array.length % 3 !== 0)
  12630. return;
  12631. this._gl.uniform3fv(uniform, array);
  12632. };
  12633. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12634. if (!uniform || array.length % 4 !== 0)
  12635. return;
  12636. this._gl.uniform4fv(uniform, array);
  12637. };
  12638. Engine.prototype.setArray = function (uniform, array) {
  12639. if (!uniform)
  12640. return;
  12641. this._gl.uniform1fv(uniform, array);
  12642. };
  12643. Engine.prototype.setArray2 = function (uniform, array) {
  12644. if (!uniform || array.length % 2 !== 0)
  12645. return;
  12646. this._gl.uniform2fv(uniform, array);
  12647. };
  12648. Engine.prototype.setArray3 = function (uniform, array) {
  12649. if (!uniform || array.length % 3 !== 0)
  12650. return;
  12651. this._gl.uniform3fv(uniform, array);
  12652. };
  12653. Engine.prototype.setArray4 = function (uniform, array) {
  12654. if (!uniform || array.length % 4 !== 0)
  12655. return;
  12656. this._gl.uniform4fv(uniform, array);
  12657. };
  12658. Engine.prototype.setMatrices = function (uniform, matrices) {
  12659. if (!uniform)
  12660. return;
  12661. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12662. };
  12663. Engine.prototype.setMatrix = function (uniform, matrix) {
  12664. if (!uniform)
  12665. return;
  12666. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12667. };
  12668. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12669. if (!uniform)
  12670. return;
  12671. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12672. };
  12673. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12674. if (!uniform)
  12675. return;
  12676. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12677. };
  12678. Engine.prototype.setInt = function (uniform, value) {
  12679. if (!uniform)
  12680. return;
  12681. this._gl.uniform1i(uniform, value);
  12682. };
  12683. Engine.prototype.setFloat = function (uniform, value) {
  12684. if (!uniform)
  12685. return;
  12686. this._gl.uniform1f(uniform, value);
  12687. };
  12688. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12689. if (!uniform)
  12690. return;
  12691. this._gl.uniform2f(uniform, x, y);
  12692. };
  12693. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12694. if (!uniform)
  12695. return;
  12696. this._gl.uniform3f(uniform, x, y, z);
  12697. };
  12698. Engine.prototype.setBool = function (uniform, bool) {
  12699. if (!uniform)
  12700. return;
  12701. this._gl.uniform1i(uniform, bool);
  12702. };
  12703. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12704. if (!uniform)
  12705. return;
  12706. this._gl.uniform4f(uniform, x, y, z, w);
  12707. };
  12708. Engine.prototype.setColor3 = function (uniform, color3) {
  12709. if (!uniform)
  12710. return;
  12711. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12712. };
  12713. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12714. if (!uniform)
  12715. return;
  12716. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12717. };
  12718. /**
  12719. * Sets a Color4 on a uniform variable
  12720. * @param uniform defines the uniform location
  12721. * @param color4 defines the value to be set
  12722. */
  12723. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12724. if (!uniform)
  12725. return;
  12726. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12727. };
  12728. // States
  12729. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12730. if (zOffset === void 0) { zOffset = 0; }
  12731. if (reverseSide === void 0) { reverseSide = false; }
  12732. // Culling
  12733. if (this._depthCullingState.cull !== culling || force) {
  12734. this._depthCullingState.cull = culling;
  12735. }
  12736. // Cull face
  12737. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12738. if (this._depthCullingState.cullFace !== cullFace || force) {
  12739. this._depthCullingState.cullFace = cullFace;
  12740. }
  12741. // Z offset
  12742. this.setZOffset(zOffset);
  12743. // Front face
  12744. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12745. if (this._depthCullingState.frontFace !== frontFace || force) {
  12746. this._depthCullingState.frontFace = frontFace;
  12747. }
  12748. };
  12749. Engine.prototype.setZOffset = function (value) {
  12750. this._depthCullingState.zOffset = value;
  12751. };
  12752. Engine.prototype.getZOffset = function () {
  12753. return this._depthCullingState.zOffset;
  12754. };
  12755. Engine.prototype.setDepthBuffer = function (enable) {
  12756. this._depthCullingState.depthTest = enable;
  12757. };
  12758. Engine.prototype.getDepthWrite = function () {
  12759. return this._depthCullingState.depthMask;
  12760. };
  12761. Engine.prototype.setDepthWrite = function (enable) {
  12762. this._depthCullingState.depthMask = enable;
  12763. };
  12764. Engine.prototype.setColorWrite = function (enable) {
  12765. this._gl.colorMask(enable, enable, enable, enable);
  12766. this._colorWrite = enable;
  12767. };
  12768. Engine.prototype.getColorWrite = function () {
  12769. return this._colorWrite;
  12770. };
  12771. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12772. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12773. };
  12774. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12775. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12776. if (this._alphaMode === mode) {
  12777. return;
  12778. }
  12779. switch (mode) {
  12780. case Engine.ALPHA_DISABLE:
  12781. this._alphaState.alphaBlend = false;
  12782. break;
  12783. case Engine.ALPHA_PREMULTIPLIED:
  12784. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12785. this._alphaState.alphaBlend = true;
  12786. break;
  12787. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12788. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12789. this._alphaState.alphaBlend = true;
  12790. break;
  12791. case Engine.ALPHA_COMBINE:
  12792. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12793. this._alphaState.alphaBlend = true;
  12794. break;
  12795. case Engine.ALPHA_ONEONE:
  12796. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12797. this._alphaState.alphaBlend = true;
  12798. break;
  12799. case Engine.ALPHA_ADD:
  12800. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12801. this._alphaState.alphaBlend = true;
  12802. break;
  12803. case Engine.ALPHA_SUBTRACT:
  12804. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12805. this._alphaState.alphaBlend = true;
  12806. break;
  12807. case Engine.ALPHA_MULTIPLY:
  12808. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12809. this._alphaState.alphaBlend = true;
  12810. break;
  12811. case Engine.ALPHA_MAXIMIZED:
  12812. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12813. this._alphaState.alphaBlend = true;
  12814. break;
  12815. case Engine.ALPHA_INTERPOLATE:
  12816. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12817. this._alphaState.alphaBlend = true;
  12818. break;
  12819. case Engine.ALPHA_SCREENMODE:
  12820. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12821. this._alphaState.alphaBlend = true;
  12822. break;
  12823. }
  12824. if (!noDepthWriteChange) {
  12825. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12826. }
  12827. this._alphaMode = mode;
  12828. };
  12829. Engine.prototype.getAlphaMode = function () {
  12830. return this._alphaMode;
  12831. };
  12832. // Textures
  12833. Engine.prototype.wipeCaches = function (bruteForce) {
  12834. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12835. return;
  12836. }
  12837. this._currentEffect = null;
  12838. // 6/8/2017: deltakosh: Should not be required anymore.
  12839. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12840. if (bruteForce) {
  12841. this.resetTextureCache();
  12842. this._currentProgram = null;
  12843. this._stencilState.reset();
  12844. this._depthCullingState.reset();
  12845. this.setDepthFunctionToLessOrEqual();
  12846. this._alphaState.reset();
  12847. }
  12848. this._resetVertexBufferBinding();
  12849. this._cachedIndexBuffer = null;
  12850. this._cachedEffectForVertexBuffers = null;
  12851. this._unbindVertexArrayObject();
  12852. this.bindIndexBuffer(null);
  12853. };
  12854. /**
  12855. * Set the compressed texture format to use, based on the formats you have, and the formats
  12856. * supported by the hardware / browser.
  12857. *
  12858. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12859. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12860. * to API arguments needed to compressed textures. This puts the burden on the container
  12861. * generator to house the arcane code for determining these for current & future formats.
  12862. *
  12863. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12864. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12865. *
  12866. * Note: The result of this call is not taken into account when a texture is base64.
  12867. *
  12868. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12869. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12870. *
  12871. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12872. * @returns The extension selected.
  12873. */
  12874. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12875. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12876. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12877. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12878. return this._textureFormatInUse = this._texturesSupported[i];
  12879. }
  12880. }
  12881. }
  12882. // actively set format to nothing, to allow this to be called more than once
  12883. // and possibly fail the 2nd time
  12884. this._textureFormatInUse = null;
  12885. return null;
  12886. };
  12887. Engine.prototype._createTexture = function () {
  12888. var texture = this._gl.createTexture();
  12889. if (!texture) {
  12890. throw new Error("Unable to create texture");
  12891. }
  12892. return texture;
  12893. };
  12894. /**
  12895. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12896. * @param {string} urlArg- This contains one of the following:
  12897. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12898. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12899. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12900. *
  12901. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12902. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12903. * @param {Scene} scene- Needed for loading to the correct scene.
  12904. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12905. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12906. * @param {callback} onError- Optional callback to be called upon failure.
  12907. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12908. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12909. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12910. *
  12911. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12912. */
  12913. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12914. var _this = this;
  12915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12916. if (onLoad === void 0) { onLoad = null; }
  12917. if (onError === void 0) { onError = null; }
  12918. if (buffer === void 0) { buffer = null; }
  12919. if (fallBack === void 0) { fallBack = null; }
  12920. if (format === void 0) { format = null; }
  12921. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12922. var fromData = url.substr(0, 5) === "data:";
  12923. var fromBlob = url.substr(0, 5) === "blob:";
  12924. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12925. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12926. // establish the file extension, if possible
  12927. var lastDot = url.lastIndexOf('.');
  12928. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12929. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12930. var isTGA = (extension.indexOf(".tga") === 0);
  12931. // determine if a ktx file should be substituted
  12932. var isKTX = false;
  12933. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12934. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12935. isKTX = true;
  12936. }
  12937. if (scene) {
  12938. scene._addPendingData(texture);
  12939. }
  12940. texture.url = url;
  12941. texture.generateMipMaps = !noMipmap;
  12942. texture.samplingMode = samplingMode;
  12943. texture.invertY = invertY;
  12944. if (!this._doNotHandleContextLost) {
  12945. // Keep a link to the buffer only if we plan to handle context lost
  12946. texture._buffer = buffer;
  12947. }
  12948. var onLoadObserver = null;
  12949. if (onLoad && !fallBack) {
  12950. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12951. }
  12952. if (!fallBack)
  12953. this._internalTexturesCache.push(texture);
  12954. var onerror = function (message, exception) {
  12955. if (scene) {
  12956. scene._removePendingData(texture);
  12957. }
  12958. if (onLoadObserver) {
  12959. texture.onLoadedObservable.remove(onLoadObserver);
  12960. }
  12961. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12962. if (isKTX) {
  12963. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12964. }
  12965. else if (BABYLON.Tools.UseFallbackTexture) {
  12966. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12967. }
  12968. if (onError) {
  12969. onError(message || "Unknown error", exception);
  12970. }
  12971. };
  12972. var callback = null;
  12973. // processing for non-image formats
  12974. if (isKTX || isTGA || isDDS) {
  12975. if (isKTX) {
  12976. callback = function (data) {
  12977. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12978. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12979. ktx.uploadLevels(_this._gl, !noMipmap);
  12980. return false;
  12981. }, samplingMode);
  12982. };
  12983. }
  12984. else if (isTGA) {
  12985. callback = function (arrayBuffer) {
  12986. var data = new Uint8Array(arrayBuffer);
  12987. var header = BABYLON.TGATools.GetTGAHeader(data);
  12988. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12989. BABYLON.TGATools.UploadContent(_this._gl, data);
  12990. return false;
  12991. }, samplingMode);
  12992. };
  12993. }
  12994. else if (isDDS) {
  12995. callback = function (data) {
  12996. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12997. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12998. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12999. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13000. return false;
  13001. }, samplingMode);
  13002. };
  13003. }
  13004. if (!buffer) {
  13005. this._loadFile(url, function (data) {
  13006. if (callback) {
  13007. callback(data);
  13008. }
  13009. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13010. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13011. });
  13012. }
  13013. else {
  13014. if (callback) {
  13015. callback(buffer);
  13016. }
  13017. }
  13018. // image format processing
  13019. }
  13020. else {
  13021. var onload = function (img) {
  13022. if (fromBlob && !_this._doNotHandleContextLost) {
  13023. // We need to store the image if we need to rebuild the texture
  13024. // in case of a webgl context lost
  13025. texture._buffer = img;
  13026. }
  13027. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13028. var gl = _this._gl;
  13029. var isPot = (img.width === potWidth && img.height === potHeight);
  13030. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13031. if (isPot) {
  13032. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13033. return false;
  13034. }
  13035. // Using shaders to rescale because canvas.drawImage is lossy
  13036. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13037. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13038. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13039. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13040. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13041. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13042. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13043. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13044. _this._releaseTexture(source);
  13045. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13046. continuationCallback();
  13047. });
  13048. return true;
  13049. }, samplingMode);
  13050. };
  13051. if (!fromData || isBase64)
  13052. if (buffer instanceof HTMLImageElement) {
  13053. onload(buffer);
  13054. }
  13055. else {
  13056. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13057. }
  13058. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13059. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13060. else
  13061. onload(buffer);
  13062. }
  13063. return texture;
  13064. };
  13065. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13066. var _this = this;
  13067. var rtt = this.createRenderTargetTexture({
  13068. width: destination.width,
  13069. height: destination.height,
  13070. }, {
  13071. generateMipMaps: false,
  13072. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13073. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13074. generateDepthBuffer: false,
  13075. generateStencilBuffer: false
  13076. });
  13077. if (!this._rescalePostProcess) {
  13078. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13079. }
  13080. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13081. _this._rescalePostProcess.onApply = function (effect) {
  13082. effect._bindTexture("textureSampler", source);
  13083. };
  13084. var hostingScene = scene;
  13085. if (!hostingScene) {
  13086. hostingScene = _this.scenes[_this.scenes.length - 1];
  13087. }
  13088. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13089. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13090. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13091. _this.unBindFramebuffer(rtt);
  13092. _this._releaseTexture(rtt);
  13093. if (onComplete) {
  13094. onComplete();
  13095. }
  13096. });
  13097. };
  13098. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13099. if (compression === void 0) { compression = null; }
  13100. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13101. if (!texture) {
  13102. return;
  13103. }
  13104. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13105. var internalFormat = this._getInternalFormat(format);
  13106. var textureType = this._getWebGLTextureType(type);
  13107. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13108. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13109. if (!this._doNotHandleContextLost) {
  13110. texture._bufferView = data;
  13111. texture.format = format;
  13112. texture.type = type;
  13113. texture.invertY = invertY;
  13114. texture._compression = compression;
  13115. }
  13116. if (texture.width % 4 !== 0) {
  13117. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13118. }
  13119. if (compression && data) {
  13120. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13121. }
  13122. else {
  13123. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13124. }
  13125. if (texture.generateMipMaps) {
  13126. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13127. }
  13128. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13129. // this.resetTextureCache();
  13130. texture.isReady = true;
  13131. };
  13132. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13133. if (compression === void 0) { compression = null; }
  13134. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13135. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13136. texture.baseWidth = width;
  13137. texture.baseHeight = height;
  13138. texture.width = width;
  13139. texture.height = height;
  13140. texture.format = format;
  13141. texture.generateMipMaps = generateMipMaps;
  13142. texture.samplingMode = samplingMode;
  13143. texture.invertY = invertY;
  13144. texture._compression = compression;
  13145. texture.type = type;
  13146. if (!this._doNotHandleContextLost) {
  13147. texture._bufferView = data;
  13148. }
  13149. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13150. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13151. // Filters
  13152. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13153. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13154. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13155. if (generateMipMaps) {
  13156. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13157. }
  13158. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13159. this._internalTexturesCache.push(texture);
  13160. return texture;
  13161. };
  13162. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13163. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13164. texture.baseWidth = width;
  13165. texture.baseHeight = height;
  13166. if (generateMipMaps) {
  13167. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13168. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13169. }
  13170. // this.resetTextureCache();
  13171. texture.width = width;
  13172. texture.height = height;
  13173. texture.isReady = false;
  13174. texture.generateMipMaps = generateMipMaps;
  13175. texture.samplingMode = samplingMode;
  13176. this.updateTextureSamplingMode(samplingMode, texture);
  13177. this._internalTexturesCache.push(texture);
  13178. return texture;
  13179. };
  13180. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13181. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13182. if (texture.isCube) {
  13183. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13184. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13185. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13186. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13187. }
  13188. else if (texture.is3D) {
  13189. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13190. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13191. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13192. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13193. }
  13194. else {
  13195. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13196. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13197. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13198. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13199. }
  13200. texture.samplingMode = samplingMode;
  13201. };
  13202. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13203. if (premulAlpha === void 0) { premulAlpha = false; }
  13204. if (!texture) {
  13205. return;
  13206. }
  13207. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13208. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13209. if (premulAlpha) {
  13210. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13211. }
  13212. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13213. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13214. if (texture.generateMipMaps) {
  13215. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13216. }
  13217. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13218. if (premulAlpha) {
  13219. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13220. }
  13221. texture.isReady = true;
  13222. };
  13223. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13224. if (!texture || texture._isDisabled) {
  13225. return;
  13226. }
  13227. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13228. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13229. try {
  13230. // Testing video texture support
  13231. if (this._videoTextureSupported === undefined) {
  13232. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13233. if (this._gl.getError() !== 0) {
  13234. this._videoTextureSupported = false;
  13235. }
  13236. else {
  13237. this._videoTextureSupported = true;
  13238. }
  13239. }
  13240. // Copy video through the current working canvas if video texture is not supported
  13241. if (!this._videoTextureSupported) {
  13242. if (!texture._workingCanvas) {
  13243. texture._workingCanvas = document.createElement("canvas");
  13244. var context = texture._workingCanvas.getContext("2d");
  13245. if (!context) {
  13246. throw new Error("Unable to get 2d context");
  13247. }
  13248. texture._workingContext = context;
  13249. texture._workingCanvas.width = texture.width;
  13250. texture._workingCanvas.height = texture.height;
  13251. }
  13252. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13253. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13254. }
  13255. else {
  13256. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13257. }
  13258. if (texture.generateMipMaps) {
  13259. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13260. }
  13261. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13262. // this.resetTextureCache();
  13263. texture.isReady = true;
  13264. }
  13265. catch (ex) {
  13266. // Something unexpected
  13267. // Let's disable the texture
  13268. texture._isDisabled = true;
  13269. }
  13270. };
  13271. /**
  13272. * Updates a depth texture Comparison Mode and Function.
  13273. * If the comparison Function is equal to 0, the mode will be set to none.
  13274. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13275. * @param texture The texture to set the comparison function for
  13276. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13277. */
  13278. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13279. if (this.webGLVersion === 1) {
  13280. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13281. return;
  13282. }
  13283. var gl = this._gl;
  13284. if (texture.isCube) {
  13285. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13286. if (comparisonFunction === 0) {
  13287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13289. }
  13290. else {
  13291. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13293. }
  13294. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13295. }
  13296. else {
  13297. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13298. if (comparisonFunction === 0) {
  13299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13301. }
  13302. else {
  13303. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13304. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13305. }
  13306. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13307. }
  13308. texture._comparisonFunction = comparisonFunction;
  13309. };
  13310. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13311. var width = size.width || size;
  13312. var height = size.height || size;
  13313. internalTexture.baseWidth = width;
  13314. internalTexture.baseHeight = height;
  13315. internalTexture.width = width;
  13316. internalTexture.height = height;
  13317. internalTexture.isReady = true;
  13318. internalTexture.samples = 1;
  13319. internalTexture.generateMipMaps = false;
  13320. internalTexture._generateDepthBuffer = true;
  13321. internalTexture._generateStencilBuffer = generateStencil;
  13322. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13323. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13324. internalTexture._comparisonFunction = comparisonFunction;
  13325. var gl = this._gl;
  13326. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13327. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13328. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13329. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13330. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13331. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13332. if (comparisonFunction === 0) {
  13333. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13334. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13335. }
  13336. else {
  13337. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13338. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13339. }
  13340. };
  13341. /**
  13342. * Creates a depth stencil texture.
  13343. * This is only available in WebGL 2 or with the depth texture extension available.
  13344. * @param size The size of face edge in the texture.
  13345. * @param options The options defining the texture.
  13346. * @returns The texture
  13347. */
  13348. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13349. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13350. if (!this._caps.depthTextureExtension) {
  13351. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13352. return internalTexture;
  13353. }
  13354. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13355. var gl = this._gl;
  13356. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13357. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13358. if (this.webGLVersion > 1) {
  13359. if (internalOptions.generateStencil) {
  13360. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13361. }
  13362. else {
  13363. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13364. }
  13365. }
  13366. else {
  13367. if (internalOptions.generateStencil) {
  13368. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13369. }
  13370. else {
  13371. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13372. }
  13373. }
  13374. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13375. return internalTexture;
  13376. };
  13377. /**
  13378. * Creates a depth stencil cube texture.
  13379. * This is only available in WebGL 2.
  13380. * @param size The size of face edge in the cube texture.
  13381. * @param options The options defining the cube texture.
  13382. * @returns The cube texture
  13383. */
  13384. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13385. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13386. internalTexture.isCube = true;
  13387. if (this.webGLVersion === 1) {
  13388. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13389. return internalTexture;
  13390. }
  13391. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13392. var gl = this._gl;
  13393. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13394. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13395. // Create the depth/stencil buffer
  13396. for (var face = 0; face < 6; face++) {
  13397. if (internalOptions.generateStencil) {
  13398. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13399. }
  13400. else {
  13401. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13402. }
  13403. }
  13404. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13405. return internalTexture;
  13406. };
  13407. /**
  13408. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13409. * @param renderTarget The render target to set the frame buffer for
  13410. */
  13411. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13412. // Create the framebuffer
  13413. var internalTexture = renderTarget.getInternalTexture();
  13414. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13415. return;
  13416. }
  13417. var gl = this._gl;
  13418. var depthStencilTexture = renderTarget.depthStencilTexture;
  13419. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13420. if (depthStencilTexture.isCube) {
  13421. if (depthStencilTexture._generateStencilBuffer) {
  13422. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13423. }
  13424. else {
  13425. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13426. }
  13427. }
  13428. else {
  13429. if (depthStencilTexture._generateStencilBuffer) {
  13430. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13431. }
  13432. else {
  13433. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13434. }
  13435. }
  13436. this.bindUnboundFramebuffer(null);
  13437. };
  13438. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13439. var fullOptions = new RenderTargetCreationOptions();
  13440. if (options !== undefined && typeof options === "object") {
  13441. fullOptions.generateMipMaps = options.generateMipMaps;
  13442. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13443. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13444. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13445. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13446. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13447. }
  13448. else {
  13449. fullOptions.generateMipMaps = options;
  13450. fullOptions.generateDepthBuffer = true;
  13451. fullOptions.generateStencilBuffer = false;
  13452. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13453. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13454. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13455. }
  13456. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13457. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13458. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13459. }
  13460. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13461. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13462. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13463. }
  13464. var gl = this._gl;
  13465. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13466. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13467. var width = size.width || size;
  13468. var height = size.height || size;
  13469. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13470. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13471. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13472. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13473. }
  13474. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13475. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13476. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13478. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13479. // Create the framebuffer
  13480. var framebuffer = gl.createFramebuffer();
  13481. this.bindUnboundFramebuffer(framebuffer);
  13482. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13483. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13484. if (fullOptions.generateMipMaps) {
  13485. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13486. }
  13487. // Unbind
  13488. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13489. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13490. this.bindUnboundFramebuffer(null);
  13491. texture._framebuffer = framebuffer;
  13492. texture.baseWidth = width;
  13493. texture.baseHeight = height;
  13494. texture.width = width;
  13495. texture.height = height;
  13496. texture.isReady = true;
  13497. texture.samples = 1;
  13498. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13499. texture.samplingMode = fullOptions.samplingMode;
  13500. texture.type = fullOptions.type;
  13501. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13502. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13503. // this.resetTextureCache();
  13504. this._internalTexturesCache.push(texture);
  13505. return texture;
  13506. };
  13507. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13508. var generateMipMaps = false;
  13509. var generateDepthBuffer = true;
  13510. var generateStencilBuffer = false;
  13511. var generateDepthTexture = false;
  13512. var textureCount = 1;
  13513. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13514. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13515. var types = [], samplingModes = [];
  13516. if (options !== undefined) {
  13517. generateMipMaps = options.generateMipMaps;
  13518. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13519. generateStencilBuffer = options.generateStencilBuffer;
  13520. generateDepthTexture = options.generateDepthTexture;
  13521. textureCount = options.textureCount || 1;
  13522. if (options.types) {
  13523. types = options.types;
  13524. }
  13525. if (options.samplingModes) {
  13526. samplingModes = options.samplingModes;
  13527. }
  13528. }
  13529. var gl = this._gl;
  13530. // Create the framebuffer
  13531. var framebuffer = gl.createFramebuffer();
  13532. this.bindUnboundFramebuffer(framebuffer);
  13533. var width = size.width || size;
  13534. var height = size.height || size;
  13535. var textures = [];
  13536. var attachments = [];
  13537. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13538. for (var i = 0; i < textureCount; i++) {
  13539. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13540. var type = types[i] || defaultType;
  13541. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13542. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13543. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13544. }
  13545. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13546. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13547. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13548. }
  13549. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13550. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13551. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13552. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13553. }
  13554. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13555. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13556. textures.push(texture);
  13557. attachments.push(attachment);
  13558. gl.activeTexture(gl["TEXTURE" + i]);
  13559. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13561. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13564. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13565. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13566. if (generateMipMaps) {
  13567. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13568. }
  13569. // Unbind
  13570. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13571. texture._framebuffer = framebuffer;
  13572. texture._depthStencilBuffer = depthStencilBuffer;
  13573. texture.baseWidth = width;
  13574. texture.baseHeight = height;
  13575. texture.width = width;
  13576. texture.height = height;
  13577. texture.isReady = true;
  13578. texture.samples = 1;
  13579. texture.generateMipMaps = generateMipMaps;
  13580. texture.samplingMode = samplingMode;
  13581. texture.type = type;
  13582. texture._generateDepthBuffer = generateDepthBuffer;
  13583. texture._generateStencilBuffer = generateStencilBuffer;
  13584. texture._attachments = attachments;
  13585. this._internalTexturesCache.push(texture);
  13586. }
  13587. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13588. // Depth texture
  13589. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13590. gl.activeTexture(gl.TEXTURE0);
  13591. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13592. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13593. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13594. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13595. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13596. 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);
  13597. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13598. depthTexture._framebuffer = framebuffer;
  13599. depthTexture.baseWidth = width;
  13600. depthTexture.baseHeight = height;
  13601. depthTexture.width = width;
  13602. depthTexture.height = height;
  13603. depthTexture.isReady = true;
  13604. depthTexture.samples = 1;
  13605. depthTexture.generateMipMaps = generateMipMaps;
  13606. depthTexture.samplingMode = gl.NEAREST;
  13607. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13608. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13609. textures.push(depthTexture);
  13610. this._internalTexturesCache.push(depthTexture);
  13611. }
  13612. gl.drawBuffers(attachments);
  13613. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13614. this.bindUnboundFramebuffer(null);
  13615. this.resetTextureCache();
  13616. return textures;
  13617. };
  13618. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13619. if (samples === void 0) { samples = 1; }
  13620. var depthStencilBuffer = null;
  13621. var gl = this._gl;
  13622. // Create the depth/stencil buffer
  13623. if (generateStencilBuffer) {
  13624. depthStencilBuffer = gl.createRenderbuffer();
  13625. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13626. if (samples > 1) {
  13627. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13628. }
  13629. else {
  13630. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13631. }
  13632. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13633. }
  13634. else if (generateDepthBuffer) {
  13635. depthStencilBuffer = gl.createRenderbuffer();
  13636. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13637. if (samples > 1) {
  13638. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13639. }
  13640. else {
  13641. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13642. }
  13643. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13644. }
  13645. return depthStencilBuffer;
  13646. };
  13647. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13648. if (this.webGLVersion < 2 || !texture) {
  13649. return 1;
  13650. }
  13651. if (texture.samples === samples) {
  13652. return samples;
  13653. }
  13654. var gl = this._gl;
  13655. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13656. // Dispose previous render buffers
  13657. if (texture._depthStencilBuffer) {
  13658. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13659. texture._depthStencilBuffer = null;
  13660. }
  13661. if (texture._MSAAFramebuffer) {
  13662. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13663. texture._MSAAFramebuffer = null;
  13664. }
  13665. if (texture._MSAARenderBuffer) {
  13666. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13667. texture._MSAARenderBuffer = null;
  13668. }
  13669. if (samples > 1) {
  13670. var framebuffer = gl.createFramebuffer();
  13671. if (!framebuffer) {
  13672. throw new Error("Unable to create multi sampled framebuffer");
  13673. }
  13674. texture._MSAAFramebuffer = framebuffer;
  13675. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13676. var colorRenderbuffer = gl.createRenderbuffer();
  13677. if (!colorRenderbuffer) {
  13678. throw new Error("Unable to create multi sampled framebuffer");
  13679. }
  13680. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13681. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13682. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13683. texture._MSAARenderBuffer = colorRenderbuffer;
  13684. }
  13685. else {
  13686. this.bindUnboundFramebuffer(texture._framebuffer);
  13687. }
  13688. texture.samples = samples;
  13689. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13690. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13691. this.bindUnboundFramebuffer(null);
  13692. return samples;
  13693. };
  13694. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13695. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13696. return 1;
  13697. }
  13698. if (textures[0].samples === samples) {
  13699. return samples;
  13700. }
  13701. var gl = this._gl;
  13702. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13703. // Dispose previous render buffers
  13704. if (textures[0]._depthStencilBuffer) {
  13705. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13706. textures[0]._depthStencilBuffer = null;
  13707. }
  13708. if (textures[0]._MSAAFramebuffer) {
  13709. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13710. textures[0]._MSAAFramebuffer = null;
  13711. }
  13712. for (var i = 0; i < textures.length; i++) {
  13713. if (textures[i]._MSAARenderBuffer) {
  13714. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13715. textures[i]._MSAARenderBuffer = null;
  13716. }
  13717. }
  13718. if (samples > 1) {
  13719. var framebuffer = gl.createFramebuffer();
  13720. if (!framebuffer) {
  13721. throw new Error("Unable to create multi sampled framebuffer");
  13722. }
  13723. this.bindUnboundFramebuffer(framebuffer);
  13724. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13725. var attachments = [];
  13726. for (var i = 0; i < textures.length; i++) {
  13727. var texture = textures[i];
  13728. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13729. var colorRenderbuffer = gl.createRenderbuffer();
  13730. if (!colorRenderbuffer) {
  13731. throw new Error("Unable to create multi sampled framebuffer");
  13732. }
  13733. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13734. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13735. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13736. texture._MSAAFramebuffer = framebuffer;
  13737. texture._MSAARenderBuffer = colorRenderbuffer;
  13738. texture.samples = samples;
  13739. texture._depthStencilBuffer = depthStencilBuffer;
  13740. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13741. attachments.push(attachment);
  13742. }
  13743. gl.drawBuffers(attachments);
  13744. }
  13745. else {
  13746. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13747. }
  13748. this.bindUnboundFramebuffer(null);
  13749. return samples;
  13750. };
  13751. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13752. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13753. };
  13754. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13755. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13756. };
  13757. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13758. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13759. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13760. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13761. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13762. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13763. }
  13764. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13765. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13766. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13767. }
  13768. var gl = this._gl;
  13769. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13770. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13771. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13772. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13773. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13774. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13775. }
  13776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13780. for (var face = 0; face < 6; face++) {
  13781. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13782. }
  13783. // Create the framebuffer
  13784. var framebuffer = gl.createFramebuffer();
  13785. this.bindUnboundFramebuffer(framebuffer);
  13786. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13787. // MipMaps
  13788. if (fullOptions.generateMipMaps) {
  13789. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13790. }
  13791. // Unbind
  13792. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13793. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13794. this.bindUnboundFramebuffer(null);
  13795. texture._framebuffer = framebuffer;
  13796. texture.width = size;
  13797. texture.height = size;
  13798. texture.isReady = true;
  13799. texture.isCube = true;
  13800. texture.samples = 1;
  13801. texture.generateMipMaps = fullOptions.generateMipMaps;
  13802. texture.samplingMode = fullOptions.samplingMode;
  13803. texture.type = fullOptions.type;
  13804. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13805. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13806. this._internalTexturesCache.push(texture);
  13807. return texture;
  13808. };
  13809. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13810. var _this = this;
  13811. if (onLoad === void 0) { onLoad = null; }
  13812. if (onError === void 0) { onError = null; }
  13813. if (forcedExtension === void 0) { forcedExtension = null; }
  13814. var callback = function (loadData) {
  13815. if (!loadData) {
  13816. if (onLoad) {
  13817. onLoad(null);
  13818. }
  13819. return;
  13820. }
  13821. var texture = loadData.texture;
  13822. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13823. texture._lodGenerationScale = scale;
  13824. texture._lodGenerationOffset = offset;
  13825. if (_this._caps.textureLOD) {
  13826. // Do not add extra process if texture lod is supported.
  13827. if (onLoad) {
  13828. onLoad(texture);
  13829. }
  13830. return;
  13831. }
  13832. var mipSlices = 3;
  13833. var gl = _this._gl;
  13834. var width = loadData.width;
  13835. if (!width) {
  13836. return;
  13837. }
  13838. var textures = [];
  13839. for (var i = 0; i < mipSlices; i++) {
  13840. //compute LOD from even spacing in smoothness (matching shader calculation)
  13841. var smoothness = i / (mipSlices - 1);
  13842. var roughness = 1 - smoothness;
  13843. var minLODIndex = offset; // roughness = 0
  13844. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13845. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13846. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13847. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13848. glTextureFromLod.isCube = true;
  13849. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13854. if (loadData.isDDS) {
  13855. var info = loadData.info;
  13856. var data = loadData.data;
  13857. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13858. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13859. }
  13860. else {
  13861. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13862. }
  13863. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13864. // Wrap in a base texture for easy binding.
  13865. var lodTexture = new BABYLON.BaseTexture(scene);
  13866. lodTexture.isCube = true;
  13867. lodTexture._texture = glTextureFromLod;
  13868. glTextureFromLod.isReady = true;
  13869. textures.push(lodTexture);
  13870. }
  13871. texture._lodTextureHigh = textures[2];
  13872. texture._lodTextureMid = textures[1];
  13873. texture._lodTextureLow = textures[0];
  13874. if (onLoad) {
  13875. onLoad(texture);
  13876. }
  13877. };
  13878. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13879. };
  13880. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13881. var _this = this;
  13882. if (onLoad === void 0) { onLoad = null; }
  13883. if (onError === void 0) { onError = null; }
  13884. if (forcedExtension === void 0) { forcedExtension = null; }
  13885. var gl = this._gl;
  13886. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13887. texture.isCube = true;
  13888. texture.url = rootUrl;
  13889. texture.generateMipMaps = !noMipmap;
  13890. if (!this._doNotHandleContextLost) {
  13891. texture._extension = forcedExtension;
  13892. texture._files = files;
  13893. }
  13894. var isKTX = false;
  13895. var isDDS = false;
  13896. var lastDot = rootUrl.lastIndexOf('.');
  13897. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13898. if (this._textureFormatInUse) {
  13899. extension = this._textureFormatInUse;
  13900. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13901. isKTX = true;
  13902. }
  13903. else {
  13904. isDDS = (extension === ".dds");
  13905. }
  13906. var onerror = function (request, exception) {
  13907. if (onError && request) {
  13908. onError(request.status + " " + request.statusText, exception);
  13909. }
  13910. };
  13911. if (isKTX) {
  13912. this._loadFile(rootUrl, function (data) {
  13913. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13914. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13915. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13916. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13917. ktx.uploadLevels(_this._gl, !noMipmap);
  13918. _this.setCubeMapTextureParams(gl, loadMipmap);
  13919. texture.width = ktx.pixelWidth;
  13920. texture.height = ktx.pixelHeight;
  13921. texture.isReady = true;
  13922. }, undefined, undefined, true, onerror);
  13923. }
  13924. else if (isDDS) {
  13925. if (files && files.length === 6) {
  13926. this._cascadeLoadFiles(scene, function (imgs) {
  13927. var info;
  13928. var loadMipmap = false;
  13929. var width = 0;
  13930. for (var index = 0; index < imgs.length; index++) {
  13931. var data = imgs[index];
  13932. info = BABYLON.DDSTools.GetDDSInfo(data);
  13933. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13934. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13935. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13936. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13937. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13938. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13939. }
  13940. texture.width = info.width;
  13941. texture.height = info.height;
  13942. texture.type = info.textureType;
  13943. width = info.width;
  13944. }
  13945. _this.setCubeMapTextureParams(gl, loadMipmap);
  13946. texture.isReady = true;
  13947. if (onLoad) {
  13948. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13949. }
  13950. }, files, onError);
  13951. }
  13952. else {
  13953. this._loadFile(rootUrl, function (data) {
  13954. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13955. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13956. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13957. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13958. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13959. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13960. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13961. }
  13962. _this.setCubeMapTextureParams(gl, loadMipmap);
  13963. texture.width = info.width;
  13964. texture.height = info.height;
  13965. texture.isReady = true;
  13966. texture.type = info.textureType;
  13967. if (onLoad) {
  13968. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13969. }
  13970. }, undefined, undefined, true, onerror);
  13971. }
  13972. }
  13973. else {
  13974. if (!files) {
  13975. throw new Error("Cannot load cubemap because files were not defined");
  13976. }
  13977. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13978. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13979. var height = width;
  13980. _this._prepareWorkingCanvas();
  13981. if (!_this._workingCanvas || !_this._workingContext) {
  13982. return;
  13983. }
  13984. _this._workingCanvas.width = width;
  13985. _this._workingCanvas.height = height;
  13986. var faces = [
  13987. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13988. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13989. ];
  13990. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13991. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13992. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13993. for (var index = 0; index < faces.length; index++) {
  13994. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13995. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13996. }
  13997. if (!noMipmap) {
  13998. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13999. }
  14000. _this.setCubeMapTextureParams(gl, !noMipmap);
  14001. texture.width = width;
  14002. texture.height = height;
  14003. texture.isReady = true;
  14004. if (format) {
  14005. texture.format = format;
  14006. }
  14007. texture.onLoadedObservable.notifyObservers(texture);
  14008. texture.onLoadedObservable.clear();
  14009. if (onLoad) {
  14010. onLoad();
  14011. }
  14012. }, files, onError);
  14013. }
  14014. this._internalTexturesCache.push(texture);
  14015. return texture;
  14016. };
  14017. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14018. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14019. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14020. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14021. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14022. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14023. // this.resetTextureCache();
  14024. };
  14025. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14026. if (compression === void 0) { compression = null; }
  14027. if (level === void 0) { level = 0; }
  14028. texture._bufferViewArray = data;
  14029. texture.format = format;
  14030. texture.type = type;
  14031. texture.invertY = invertY;
  14032. texture._compression = compression;
  14033. var gl = this._gl;
  14034. var textureType = this._getWebGLTextureType(type);
  14035. var internalFormat = this._getInternalFormat(format);
  14036. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14037. var needConversion = false;
  14038. if (internalFormat === gl.RGB) {
  14039. internalFormat = gl.RGBA;
  14040. needConversion = true;
  14041. }
  14042. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14043. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14044. if (texture.width % 4 !== 0) {
  14045. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14046. }
  14047. // Data are known to be in +X +Y +Z -X -Y -Z
  14048. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14049. var faceData = data[faceIndex];
  14050. if (compression) {
  14051. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14052. }
  14053. else {
  14054. if (needConversion) {
  14055. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14056. }
  14057. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14058. }
  14059. }
  14060. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14061. if (isPot && texture.generateMipMaps && level === 0) {
  14062. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14063. }
  14064. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14065. // this.resetTextureCache();
  14066. texture.isReady = true;
  14067. };
  14068. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14069. if (compression === void 0) { compression = null; }
  14070. var gl = this._gl;
  14071. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14072. texture.isCube = true;
  14073. texture.generateMipMaps = generateMipMaps;
  14074. texture.format = format;
  14075. texture.type = type;
  14076. if (!this._doNotHandleContextLost) {
  14077. texture._bufferViewArray = data;
  14078. }
  14079. var textureType = this._getWebGLTextureType(type);
  14080. var internalFormat = this._getInternalFormat(format);
  14081. if (internalFormat === gl.RGB) {
  14082. internalFormat = gl.RGBA;
  14083. }
  14084. var width = size;
  14085. var height = width;
  14086. texture.width = width;
  14087. texture.height = height;
  14088. // Double check on POT to generate Mips.
  14089. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14090. if (!isPot) {
  14091. generateMipMaps = false;
  14092. }
  14093. // Upload data if needed. The texture won't be ready until then.
  14094. if (data) {
  14095. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14096. }
  14097. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14098. // Filters
  14099. if (data && generateMipMaps) {
  14100. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14101. }
  14102. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14104. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14105. }
  14106. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14108. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14109. }
  14110. else {
  14111. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14114. }
  14115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14116. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14117. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14118. return texture;
  14119. };
  14120. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14121. var _this = this;
  14122. if (onLoad === void 0) { onLoad = null; }
  14123. if (onError === void 0) { onError = null; }
  14124. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14125. if (invertY === void 0) { invertY = false; }
  14126. var gl = this._gl;
  14127. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14128. scene._addPendingData(texture);
  14129. texture.url = url;
  14130. this._internalTexturesCache.push(texture);
  14131. var onerror = function (request, exception) {
  14132. scene._removePendingData(texture);
  14133. if (onError && request) {
  14134. onError(request.status + " " + request.statusText, exception);
  14135. }
  14136. };
  14137. var internalCallback = function (data) {
  14138. var width = texture.width;
  14139. var faceDataArrays = callback(data);
  14140. if (!faceDataArrays) {
  14141. return;
  14142. }
  14143. if (mipmmapGenerator) {
  14144. var textureType = _this._getWebGLTextureType(type);
  14145. var internalFormat = _this._getInternalFormat(format);
  14146. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14147. var needConversion = false;
  14148. if (internalFormat === gl.RGB) {
  14149. internalFormat = gl.RGBA;
  14150. needConversion = true;
  14151. }
  14152. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14153. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14154. var mipData = mipmmapGenerator(faceDataArrays);
  14155. for (var level = 0; level < mipData.length; level++) {
  14156. var mipSize = width >> level;
  14157. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14158. var mipFaceData = mipData[level][faceIndex];
  14159. if (needConversion) {
  14160. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14161. }
  14162. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14163. }
  14164. }
  14165. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14166. }
  14167. else {
  14168. texture.generateMipMaps = !noMipmap;
  14169. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14170. }
  14171. texture.isReady = true;
  14172. // this.resetTextureCache();
  14173. scene._removePendingData(texture);
  14174. if (onLoad) {
  14175. onLoad();
  14176. }
  14177. };
  14178. this._loadFile(url, function (data) {
  14179. internalCallback(data);
  14180. }, undefined, scene.database, true, onerror);
  14181. return texture;
  14182. };
  14183. ;
  14184. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14185. if (compression === void 0) { compression = null; }
  14186. var internalFormat = this._getInternalFormat(format);
  14187. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14188. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14189. if (!this._doNotHandleContextLost) {
  14190. texture._bufferView = data;
  14191. texture.format = format;
  14192. texture.invertY = invertY;
  14193. texture._compression = compression;
  14194. }
  14195. if (texture.width % 4 !== 0) {
  14196. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14197. }
  14198. if (compression && data) {
  14199. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14200. }
  14201. else {
  14202. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14203. }
  14204. if (texture.generateMipMaps) {
  14205. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14206. }
  14207. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14208. // this.resetTextureCache();
  14209. texture.isReady = true;
  14210. };
  14211. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14212. if (compression === void 0) { compression = null; }
  14213. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14214. texture.baseWidth = width;
  14215. texture.baseHeight = height;
  14216. texture.baseDepth = depth;
  14217. texture.width = width;
  14218. texture.height = height;
  14219. texture.depth = depth;
  14220. texture.format = format;
  14221. texture.generateMipMaps = generateMipMaps;
  14222. texture.samplingMode = samplingMode;
  14223. texture.is3D = true;
  14224. if (!this._doNotHandleContextLost) {
  14225. texture._bufferView = data;
  14226. }
  14227. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14228. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14229. // Filters
  14230. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14231. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14232. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14233. if (generateMipMaps) {
  14234. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14235. }
  14236. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14237. this._internalTexturesCache.push(texture);
  14238. return texture;
  14239. };
  14240. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14241. var gl = this._gl;
  14242. if (!gl) {
  14243. return;
  14244. }
  14245. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14248. if (!noMipmap && !isCompressed) {
  14249. gl.generateMipmap(gl.TEXTURE_2D);
  14250. }
  14251. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14252. // this.resetTextureCache();
  14253. if (scene) {
  14254. scene._removePendingData(texture);
  14255. }
  14256. texture.onLoadedObservable.notifyObservers(texture);
  14257. texture.onLoadedObservable.clear();
  14258. };
  14259. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14260. var _this = this;
  14261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14262. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14263. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14264. var gl = this._gl;
  14265. if (!gl) {
  14266. return;
  14267. }
  14268. if (!texture._webGLTexture) {
  14269. // this.resetTextureCache();
  14270. if (scene) {
  14271. scene._removePendingData(texture);
  14272. }
  14273. return;
  14274. }
  14275. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14276. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14277. texture.baseWidth = width;
  14278. texture.baseHeight = height;
  14279. texture.width = potWidth;
  14280. texture.height = potHeight;
  14281. texture.isReady = true;
  14282. if (processFunction(potWidth, potHeight, function () {
  14283. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14284. })) {
  14285. // Returning as texture needs extra async steps
  14286. return;
  14287. }
  14288. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14289. };
  14290. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14291. // Create new RGBA data container.
  14292. var rgbaData;
  14293. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14294. rgbaData = new Float32Array(width * height * 4);
  14295. }
  14296. else {
  14297. rgbaData = new Uint32Array(width * height * 4);
  14298. }
  14299. // Convert each pixel.
  14300. for (var x = 0; x < width; x++) {
  14301. for (var y = 0; y < height; y++) {
  14302. var index = (y * width + x) * 3;
  14303. var newIndex = (y * width + x) * 4;
  14304. // Map Old Value to new value.
  14305. rgbaData[newIndex + 0] = rgbData[index + 0];
  14306. rgbaData[newIndex + 1] = rgbData[index + 1];
  14307. rgbaData[newIndex + 2] = rgbData[index + 2];
  14308. // Add fully opaque alpha channel.
  14309. rgbaData[newIndex + 3] = 1;
  14310. }
  14311. }
  14312. return rgbaData;
  14313. };
  14314. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14315. var gl = this._gl;
  14316. if (texture._framebuffer) {
  14317. gl.deleteFramebuffer(texture._framebuffer);
  14318. texture._framebuffer = null;
  14319. }
  14320. if (texture._depthStencilBuffer) {
  14321. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14322. texture._depthStencilBuffer = null;
  14323. }
  14324. if (texture._MSAAFramebuffer) {
  14325. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14326. texture._MSAAFramebuffer = null;
  14327. }
  14328. if (texture._MSAARenderBuffer) {
  14329. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14330. texture._MSAARenderBuffer = null;
  14331. }
  14332. };
  14333. Engine.prototype._releaseTexture = function (texture) {
  14334. var gl = this._gl;
  14335. this._releaseFramebufferObjects(texture);
  14336. gl.deleteTexture(texture._webGLTexture);
  14337. // Unbind channels
  14338. this.unbindAllTextures();
  14339. var index = this._internalTexturesCache.indexOf(texture);
  14340. if (index !== -1) {
  14341. this._internalTexturesCache.splice(index, 1);
  14342. }
  14343. // Integrated fixed lod samplers.
  14344. if (texture._lodTextureHigh) {
  14345. texture._lodTextureHigh.dispose();
  14346. }
  14347. if (texture._lodTextureMid) {
  14348. texture._lodTextureMid.dispose();
  14349. }
  14350. if (texture._lodTextureLow) {
  14351. texture._lodTextureLow.dispose();
  14352. }
  14353. };
  14354. Engine.prototype.setProgram = function (program) {
  14355. if (this._currentProgram !== program) {
  14356. this._gl.useProgram(program);
  14357. this._currentProgram = program;
  14358. }
  14359. };
  14360. Engine.prototype.bindSamplers = function (effect) {
  14361. this.setProgram(effect.getProgram());
  14362. var samplers = effect.getSamplers();
  14363. for (var index = 0; index < samplers.length; index++) {
  14364. var uniform = effect.getUniform(samplers[index]);
  14365. if (uniform) {
  14366. this._boundUniforms[index] = uniform;
  14367. }
  14368. }
  14369. this._currentEffect = null;
  14370. };
  14371. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14372. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14373. return;
  14374. }
  14375. // Remove
  14376. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14377. // Bind last to it
  14378. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14379. // Bind to dummy
  14380. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14381. };
  14382. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14383. if (!internalTexture) {
  14384. return -1;
  14385. }
  14386. internalTexture._initialSlot = channel;
  14387. if (this.disableTextureBindingOptimization) {
  14388. if (channel !== internalTexture._designatedSlot) {
  14389. this._textureCollisions.addCount(1, false);
  14390. }
  14391. }
  14392. else {
  14393. if (channel !== internalTexture._designatedSlot) {
  14394. if (internalTexture._designatedSlot > -1) {
  14395. return internalTexture._designatedSlot;
  14396. }
  14397. else {
  14398. // No slot for this texture, let's pick a new one (if we find a free slot)
  14399. if (this._nextFreeTextureSlots.length) {
  14400. return this._nextFreeTextureSlots[0];
  14401. }
  14402. // We need to recycle the oldest bound texture, sorry.
  14403. this._textureCollisions.addCount(1, false);
  14404. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14405. }
  14406. }
  14407. }
  14408. return channel;
  14409. };
  14410. Engine.prototype._linkTrackers = function (previous, next) {
  14411. previous.next = next;
  14412. next.previous = previous;
  14413. };
  14414. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14415. var currentSlot = internalTexture._designatedSlot;
  14416. if (currentSlot === -1) {
  14417. return -1;
  14418. }
  14419. internalTexture._designatedSlot = -1;
  14420. if (this.disableTextureBindingOptimization) {
  14421. return -1;
  14422. }
  14423. // Remove from bound list
  14424. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14425. // Free the slot
  14426. this._boundTexturesCache[currentSlot] = null;
  14427. this._nextFreeTextureSlots.push(currentSlot);
  14428. return currentSlot;
  14429. };
  14430. Engine.prototype._activateCurrentTexture = function () {
  14431. if (this._currentTextureChannel !== this._activeChannel) {
  14432. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14433. this._currentTextureChannel = this._activeChannel;
  14434. }
  14435. };
  14436. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14437. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14438. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14439. this._activeChannel = texture._designatedSlot;
  14440. }
  14441. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14442. var isTextureForRendering = texture && texture._initialSlot > -1;
  14443. if (currentTextureBound !== texture) {
  14444. if (currentTextureBound) {
  14445. this._removeDesignatedSlot(currentTextureBound);
  14446. }
  14447. this._activateCurrentTexture();
  14448. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14449. this._boundTexturesCache[this._activeChannel] = texture;
  14450. if (texture) {
  14451. if (!this.disableTextureBindingOptimization) {
  14452. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14453. if (slotIndex > -1) {
  14454. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14455. }
  14456. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14457. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14458. }
  14459. texture._designatedSlot = this._activeChannel;
  14460. }
  14461. }
  14462. else if (forTextureDataUpdate) {
  14463. this._activateCurrentTexture();
  14464. }
  14465. if (isTextureForRendering && !forTextureDataUpdate) {
  14466. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14467. }
  14468. };
  14469. Engine.prototype._bindTexture = function (channel, texture) {
  14470. if (channel < 0) {
  14471. return;
  14472. }
  14473. if (texture) {
  14474. channel = this._getCorrectTextureChannel(channel, texture);
  14475. }
  14476. this._activeChannel = channel;
  14477. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14478. };
  14479. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14480. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14481. };
  14482. Engine.prototype.unbindAllTextures = function () {
  14483. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14484. this._activeChannel = channel;
  14485. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14486. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14487. if (this.webGLVersion > 1) {
  14488. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14489. }
  14490. }
  14491. };
  14492. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14493. if (channel < 0) {
  14494. return;
  14495. }
  14496. if (uniform) {
  14497. this._boundUniforms[channel] = uniform;
  14498. }
  14499. this._setTexture(channel, texture);
  14500. };
  14501. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14502. var uniform = this._boundUniforms[sourceSlot];
  14503. if (uniform._currentState === destination) {
  14504. return;
  14505. }
  14506. this._gl.uniform1i(uniform, destination);
  14507. uniform._currentState = destination;
  14508. };
  14509. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14510. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14511. // Not ready?
  14512. if (!texture) {
  14513. if (this._boundTexturesCache[channel] != null) {
  14514. this._activeChannel = channel;
  14515. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14516. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14517. if (this.webGLVersion > 1) {
  14518. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14519. }
  14520. }
  14521. return false;
  14522. }
  14523. // Video
  14524. if (texture.video) {
  14525. this._activeChannel = channel;
  14526. texture.update();
  14527. }
  14528. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14529. texture.delayLoad();
  14530. return false;
  14531. }
  14532. var internalTexture;
  14533. if (texture.isReady()) {
  14534. internalTexture = texture.getInternalTexture();
  14535. }
  14536. else if (texture.isCube) {
  14537. internalTexture = this.emptyCubeTexture;
  14538. }
  14539. else if (texture.is3D) {
  14540. internalTexture = this.emptyTexture3D;
  14541. }
  14542. else {
  14543. internalTexture = this.emptyTexture;
  14544. }
  14545. if (!isPartOfTextureArray) {
  14546. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14547. }
  14548. if (this._boundTexturesCache[channel] === internalTexture) {
  14549. this._moveBoundTextureOnTop(internalTexture);
  14550. if (!isPartOfTextureArray) {
  14551. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14552. }
  14553. return false;
  14554. }
  14555. this._activeChannel = channel;
  14556. if (internalTexture && internalTexture.is3D) {
  14557. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14558. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14559. internalTexture._cachedWrapU = texture.wrapU;
  14560. switch (texture.wrapU) {
  14561. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14562. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14563. break;
  14564. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14565. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14566. break;
  14567. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14568. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14569. break;
  14570. }
  14571. }
  14572. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14573. internalTexture._cachedWrapV = texture.wrapV;
  14574. switch (texture.wrapV) {
  14575. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14576. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14577. break;
  14578. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14579. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14580. break;
  14581. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14582. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14583. break;
  14584. }
  14585. }
  14586. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14587. internalTexture._cachedWrapR = texture.wrapR;
  14588. switch (texture.wrapR) {
  14589. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14590. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14591. break;
  14592. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14593. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14594. break;
  14595. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14596. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14597. break;
  14598. }
  14599. }
  14600. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14601. }
  14602. else if (internalTexture && internalTexture.isCube) {
  14603. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14604. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14605. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14606. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14607. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14608. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14609. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14610. }
  14611. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14612. }
  14613. else {
  14614. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14615. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14616. internalTexture._cachedWrapU = texture.wrapU;
  14617. switch (texture.wrapU) {
  14618. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14619. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14620. break;
  14621. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14622. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14623. break;
  14624. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14626. break;
  14627. }
  14628. }
  14629. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14630. internalTexture._cachedWrapV = texture.wrapV;
  14631. switch (texture.wrapV) {
  14632. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14633. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14634. break;
  14635. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14636. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14637. break;
  14638. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14639. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14640. break;
  14641. }
  14642. }
  14643. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14644. }
  14645. return true;
  14646. };
  14647. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14648. if (channel < 0 || !uniform) {
  14649. return;
  14650. }
  14651. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14652. this._textureUnits = new Int32Array(textures.length);
  14653. }
  14654. for (var i = 0; i < textures.length; i++) {
  14655. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14656. }
  14657. this._gl.uniform1iv(uniform, this._textureUnits);
  14658. for (var index = 0; index < textures.length; index++) {
  14659. this._setTexture(this._textureUnits[index], textures[index], true);
  14660. }
  14661. };
  14662. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14663. var internalTexture = texture.getInternalTexture();
  14664. if (!internalTexture) {
  14665. return;
  14666. }
  14667. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14668. var value = texture.anisotropicFilteringLevel;
  14669. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14670. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14671. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14672. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14673. }
  14674. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14675. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14676. internalTexture._cachedAnisotropicFilteringLevel = value;
  14677. }
  14678. };
  14679. Engine.prototype.readPixels = function (x, y, width, height) {
  14680. var data = new Uint8Array(height * width * 4);
  14681. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14682. return data;
  14683. };
  14684. /**
  14685. * Add an externaly attached data from its key.
  14686. * This method call will fail and return false, if such key already exists.
  14687. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14688. * @param key the unique key that identifies the data
  14689. * @param data the data object to associate to the key for this Engine instance
  14690. * @return true if no such key were already present and the data was added successfully, false otherwise
  14691. */
  14692. Engine.prototype.addExternalData = function (key, data) {
  14693. if (!this._externalData) {
  14694. this._externalData = new BABYLON.StringDictionary();
  14695. }
  14696. return this._externalData.add(key, data);
  14697. };
  14698. /**
  14699. * Get an externaly attached data from its key
  14700. * @param key the unique key that identifies the data
  14701. * @return the associated data, if present (can be null), or undefined if not present
  14702. */
  14703. Engine.prototype.getExternalData = function (key) {
  14704. if (!this._externalData) {
  14705. this._externalData = new BABYLON.StringDictionary();
  14706. }
  14707. return this._externalData.get(key);
  14708. };
  14709. /**
  14710. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14711. * @param key the unique key that identifies the data
  14712. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14713. * @return the associated data, can be null if the factory returned null.
  14714. */
  14715. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14716. if (!this._externalData) {
  14717. this._externalData = new BABYLON.StringDictionary();
  14718. }
  14719. return this._externalData.getOrAddWithFactory(key, factory);
  14720. };
  14721. /**
  14722. * Remove an externaly attached data from the Engine instance
  14723. * @param key the unique key that identifies the data
  14724. * @return true if the data was successfully removed, false if it doesn't exist
  14725. */
  14726. Engine.prototype.removeExternalData = function (key) {
  14727. if (!this._externalData) {
  14728. this._externalData = new BABYLON.StringDictionary();
  14729. }
  14730. return this._externalData.remove(key);
  14731. };
  14732. Engine.prototype.unbindAllAttributes = function () {
  14733. if (this._mustWipeVertexAttributes) {
  14734. this._mustWipeVertexAttributes = false;
  14735. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14736. this._gl.disableVertexAttribArray(i);
  14737. this._vertexAttribArraysEnabled[i] = false;
  14738. this._currentBufferPointers[i].active = false;
  14739. }
  14740. return;
  14741. }
  14742. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14743. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14744. continue;
  14745. }
  14746. this._gl.disableVertexAttribArray(i);
  14747. this._vertexAttribArraysEnabled[i] = false;
  14748. this._currentBufferPointers[i].active = false;
  14749. }
  14750. };
  14751. Engine.prototype.releaseEffects = function () {
  14752. for (var name in this._compiledEffects) {
  14753. this._deleteProgram(this._compiledEffects[name]._program);
  14754. }
  14755. this._compiledEffects = {};
  14756. };
  14757. // Dispose
  14758. Engine.prototype.dispose = function () {
  14759. this.hideLoadingUI();
  14760. this.stopRenderLoop();
  14761. // Release postProcesses
  14762. while (this.postProcesses.length) {
  14763. this.postProcesses[0].dispose();
  14764. }
  14765. // Empty texture
  14766. if (this._emptyTexture) {
  14767. this._releaseTexture(this._emptyTexture);
  14768. this._emptyTexture = null;
  14769. }
  14770. if (this._emptyCubeTexture) {
  14771. this._releaseTexture(this._emptyCubeTexture);
  14772. this._emptyCubeTexture = null;
  14773. }
  14774. // Rescale PP
  14775. if (this._rescalePostProcess) {
  14776. this._rescalePostProcess.dispose();
  14777. }
  14778. // Release scenes
  14779. while (this.scenes.length) {
  14780. this.scenes[0].dispose();
  14781. }
  14782. // Release audio engine
  14783. if (Engine.audioEngine) {
  14784. Engine.audioEngine.dispose();
  14785. }
  14786. // Release effects
  14787. this.releaseEffects();
  14788. // Unbind
  14789. this.unbindAllAttributes();
  14790. if (this._dummyFramebuffer) {
  14791. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14792. }
  14793. //WebVR
  14794. this.disableVR();
  14795. // Events
  14796. if (BABYLON.Tools.IsWindowObjectExist()) {
  14797. window.removeEventListener("blur", this._onBlur);
  14798. window.removeEventListener("focus", this._onFocus);
  14799. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14800. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14801. if (this._renderingCanvas) {
  14802. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14803. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14804. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14805. if (!this._doNotHandleContextLost) {
  14806. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14807. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14808. }
  14809. }
  14810. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14811. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14812. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14813. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14814. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14815. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14816. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14817. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14818. if (this._onVrDisplayConnect) {
  14819. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14820. if (this._onVrDisplayDisconnect) {
  14821. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14822. }
  14823. if (this._onVrDisplayPresentChange) {
  14824. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14825. }
  14826. this._onVrDisplayConnect = null;
  14827. this._onVrDisplayDisconnect = null;
  14828. }
  14829. }
  14830. // Remove from Instances
  14831. var index = Engine.Instances.indexOf(this);
  14832. if (index >= 0) {
  14833. Engine.Instances.splice(index, 1);
  14834. }
  14835. this._workingCanvas = null;
  14836. this._workingContext = null;
  14837. this._currentBufferPointers = [];
  14838. this._renderingCanvas = null;
  14839. this._currentProgram = null;
  14840. this._bindedRenderFunction = null;
  14841. this.onResizeObservable.clear();
  14842. this.onCanvasBlurObservable.clear();
  14843. this.onCanvasFocusObservable.clear();
  14844. this.onCanvasPointerOutObservable.clear();
  14845. this.onBeginFrameObservable.clear();
  14846. this.onEndFrameObservable.clear();
  14847. BABYLON.Effect.ResetCache();
  14848. // Abort active requests
  14849. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14850. var request = _a[_i];
  14851. request.abort();
  14852. }
  14853. };
  14854. // Loading screen
  14855. Engine.prototype.displayLoadingUI = function () {
  14856. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14857. return;
  14858. }
  14859. var loadingScreen = this.loadingScreen;
  14860. if (loadingScreen) {
  14861. loadingScreen.displayLoadingUI();
  14862. }
  14863. };
  14864. Engine.prototype.hideLoadingUI = function () {
  14865. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14866. return;
  14867. }
  14868. var loadingScreen = this.loadingScreen;
  14869. if (loadingScreen) {
  14870. loadingScreen.hideLoadingUI();
  14871. }
  14872. };
  14873. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14874. get: function () {
  14875. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14876. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14877. return this._loadingScreen;
  14878. },
  14879. set: function (loadingScreen) {
  14880. this._loadingScreen = loadingScreen;
  14881. },
  14882. enumerable: true,
  14883. configurable: true
  14884. });
  14885. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14886. set: function (text) {
  14887. this.loadingScreen.loadingUIText = text;
  14888. },
  14889. enumerable: true,
  14890. configurable: true
  14891. });
  14892. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14893. set: function (color) {
  14894. this.loadingScreen.loadingUIBackgroundColor = color;
  14895. },
  14896. enumerable: true,
  14897. configurable: true
  14898. });
  14899. Engine.prototype.attachContextLostEvent = function (callback) {
  14900. if (this._renderingCanvas) {
  14901. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14902. }
  14903. };
  14904. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14905. if (this._renderingCanvas) {
  14906. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14907. }
  14908. };
  14909. Engine.prototype.getVertexShaderSource = function (program) {
  14910. var shaders = this._gl.getAttachedShaders(program);
  14911. if (!shaders) {
  14912. return null;
  14913. }
  14914. return this._gl.getShaderSource(shaders[0]);
  14915. };
  14916. Engine.prototype.getFragmentShaderSource = function (program) {
  14917. var shaders = this._gl.getAttachedShaders(program);
  14918. if (!shaders) {
  14919. return null;
  14920. }
  14921. return this._gl.getShaderSource(shaders[1]);
  14922. };
  14923. Engine.prototype.getError = function () {
  14924. return this._gl.getError();
  14925. };
  14926. // FPS
  14927. Engine.prototype.getFps = function () {
  14928. return this._fps;
  14929. };
  14930. Engine.prototype.getDeltaTime = function () {
  14931. return this._deltaTime;
  14932. };
  14933. Engine.prototype._measureFps = function () {
  14934. this._performanceMonitor.sampleFrame();
  14935. this._fps = this._performanceMonitor.averageFPS;
  14936. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14937. };
  14938. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14939. if (faceIndex === void 0) { faceIndex = -1; }
  14940. var gl = this._gl;
  14941. if (!this._dummyFramebuffer) {
  14942. var dummy = gl.createFramebuffer();
  14943. if (!dummy) {
  14944. throw new Error("Unable to create dummy framebuffer");
  14945. }
  14946. this._dummyFramebuffer = dummy;
  14947. }
  14948. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14949. if (faceIndex > -1) {
  14950. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14951. }
  14952. else {
  14953. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14954. }
  14955. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14956. var buffer;
  14957. switch (readType) {
  14958. case gl.UNSIGNED_BYTE:
  14959. buffer = new Uint8Array(4 * width * height);
  14960. readType = gl.UNSIGNED_BYTE;
  14961. break;
  14962. default:
  14963. buffer = new Float32Array(4 * width * height);
  14964. readType = gl.FLOAT;
  14965. break;
  14966. }
  14967. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14968. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14969. return buffer;
  14970. };
  14971. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14972. if (this._webGLVersion > 1) {
  14973. return this._caps.colorBufferFloat;
  14974. }
  14975. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14976. };
  14977. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14978. if (this._webGLVersion > 1) {
  14979. return this._caps.colorBufferFloat;
  14980. }
  14981. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14982. };
  14983. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14984. Engine.prototype._canRenderToFramebuffer = function (type) {
  14985. var gl = this._gl;
  14986. //clear existing errors
  14987. while (gl.getError() !== gl.NO_ERROR) { }
  14988. var successful = true;
  14989. var texture = gl.createTexture();
  14990. gl.bindTexture(gl.TEXTURE_2D, texture);
  14991. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14992. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14993. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14994. var fb = gl.createFramebuffer();
  14995. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14996. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14997. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14998. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14999. successful = successful && (gl.getError() === gl.NO_ERROR);
  15000. //try render by clearing frame buffer's color buffer
  15001. if (successful) {
  15002. gl.clear(gl.COLOR_BUFFER_BIT);
  15003. successful = successful && (gl.getError() === gl.NO_ERROR);
  15004. }
  15005. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15006. if (successful) {
  15007. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15008. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15009. var readFormat = gl.RGBA;
  15010. var readType = gl.UNSIGNED_BYTE;
  15011. var buffer = new Uint8Array(4);
  15012. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15013. successful = successful && (gl.getError() === gl.NO_ERROR);
  15014. }
  15015. //clean up
  15016. gl.deleteTexture(texture);
  15017. gl.deleteFramebuffer(fb);
  15018. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15019. //clear accumulated errors
  15020. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15021. return successful;
  15022. };
  15023. Engine.prototype._getWebGLTextureType = function (type) {
  15024. if (type === Engine.TEXTURETYPE_FLOAT) {
  15025. return this._gl.FLOAT;
  15026. }
  15027. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15028. // Add Half Float Constant.
  15029. return this._gl.HALF_FLOAT_OES;
  15030. }
  15031. return this._gl.UNSIGNED_BYTE;
  15032. };
  15033. ;
  15034. Engine.prototype._getInternalFormat = function (format) {
  15035. var internalFormat = this._gl.RGBA;
  15036. switch (format) {
  15037. case Engine.TEXTUREFORMAT_ALPHA:
  15038. internalFormat = this._gl.ALPHA;
  15039. break;
  15040. case Engine.TEXTUREFORMAT_LUMINANCE:
  15041. internalFormat = this._gl.LUMINANCE;
  15042. break;
  15043. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15044. internalFormat = this._gl.LUMINANCE_ALPHA;
  15045. break;
  15046. case Engine.TEXTUREFORMAT_RGB:
  15047. case Engine.TEXTUREFORMAT_RGB32F:
  15048. internalFormat = this._gl.RGB;
  15049. break;
  15050. case Engine.TEXTUREFORMAT_RGBA:
  15051. case Engine.TEXTUREFORMAT_RGBA32F:
  15052. internalFormat = this._gl.RGBA;
  15053. break;
  15054. case Engine.TEXTUREFORMAT_R32F:
  15055. internalFormat = this._gl.RED;
  15056. break;
  15057. case Engine.TEXTUREFORMAT_RG32F:
  15058. internalFormat = this._gl.RG;
  15059. break;
  15060. }
  15061. return internalFormat;
  15062. };
  15063. /** @ignore */
  15064. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15065. if (this._webGLVersion === 1) {
  15066. if (format) {
  15067. switch (format) {
  15068. case Engine.TEXTUREFORMAT_LUMINANCE:
  15069. return this._gl.LUMINANCE;
  15070. }
  15071. }
  15072. return this._gl.RGBA;
  15073. }
  15074. if (type === Engine.TEXTURETYPE_FLOAT) {
  15075. if (format) {
  15076. switch (format) {
  15077. case Engine.TEXTUREFORMAT_R32F:
  15078. return this._gl.R32F;
  15079. case Engine.TEXTUREFORMAT_RG32F:
  15080. return this._gl.RG32F;
  15081. case Engine.TEXTUREFORMAT_RGB32F:
  15082. return this._gl.RGB32F;
  15083. }
  15084. }
  15085. return this._gl.RGBA32F;
  15086. }
  15087. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15088. return this._gl.RGBA16F;
  15089. }
  15090. if (format) {
  15091. switch (format) {
  15092. case Engine.TEXTUREFORMAT_LUMINANCE:
  15093. return this._gl.LUMINANCE;
  15094. }
  15095. }
  15096. return this._gl.RGBA;
  15097. };
  15098. ;
  15099. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15100. if (type === Engine.TEXTURETYPE_FLOAT) {
  15101. return this._gl.RGBA32F;
  15102. }
  15103. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15104. return this._gl.RGBA16F;
  15105. }
  15106. return this._gl.RGBA8;
  15107. };
  15108. ;
  15109. Engine.prototype.createQuery = function () {
  15110. return this._gl.createQuery();
  15111. };
  15112. Engine.prototype.deleteQuery = function (query) {
  15113. this._gl.deleteQuery(query);
  15114. return this;
  15115. };
  15116. Engine.prototype.isQueryResultAvailable = function (query) {
  15117. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15118. };
  15119. Engine.prototype.getQueryResult = function (query) {
  15120. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15121. };
  15122. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15123. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15124. this._gl.beginQuery(glAlgorithm, query);
  15125. return this;
  15126. };
  15127. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15128. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15129. this._gl.endQuery(glAlgorithm);
  15130. return this;
  15131. };
  15132. /* Time queries */
  15133. Engine.prototype._createTimeQuery = function () {
  15134. var timerQuery = this._caps.timerQuery;
  15135. if (timerQuery.createQueryEXT) {
  15136. return timerQuery.createQueryEXT();
  15137. }
  15138. return this.createQuery();
  15139. };
  15140. Engine.prototype._deleteTimeQuery = function (query) {
  15141. var timerQuery = this._caps.timerQuery;
  15142. if (timerQuery.deleteQueryEXT) {
  15143. timerQuery.deleteQueryEXT(query);
  15144. return;
  15145. }
  15146. this.deleteQuery(query);
  15147. };
  15148. Engine.prototype._getTimeQueryResult = function (query) {
  15149. var timerQuery = this._caps.timerQuery;
  15150. if (timerQuery.getQueryObjectEXT) {
  15151. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15152. }
  15153. return this.getQueryResult(query);
  15154. };
  15155. Engine.prototype._getTimeQueryAvailability = function (query) {
  15156. var timerQuery = this._caps.timerQuery;
  15157. if (timerQuery.getQueryObjectEXT) {
  15158. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15159. }
  15160. return this.isQueryResultAvailable(query);
  15161. };
  15162. Engine.prototype.startTimeQuery = function () {
  15163. var timerQuery = this._caps.timerQuery;
  15164. if (!timerQuery) {
  15165. return null;
  15166. }
  15167. var token = new BABYLON._TimeToken();
  15168. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15169. if (this._caps.canUseTimestampForTimerQuery) {
  15170. token._startTimeQuery = this._createTimeQuery();
  15171. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15172. }
  15173. else {
  15174. if (this._currentNonTimestampToken) {
  15175. return this._currentNonTimestampToken;
  15176. }
  15177. token._timeElapsedQuery = this._createTimeQuery();
  15178. if (timerQuery.beginQueryEXT) {
  15179. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15180. }
  15181. else {
  15182. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15183. }
  15184. this._currentNonTimestampToken = token;
  15185. }
  15186. return token;
  15187. };
  15188. Engine.prototype.endTimeQuery = function (token) {
  15189. var timerQuery = this._caps.timerQuery;
  15190. if (!timerQuery || !token) {
  15191. return -1;
  15192. }
  15193. if (this._caps.canUseTimestampForTimerQuery) {
  15194. if (!token._startTimeQuery) {
  15195. return -1;
  15196. }
  15197. if (!token._endTimeQuery) {
  15198. token._endTimeQuery = this._createTimeQuery();
  15199. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15200. }
  15201. }
  15202. else if (!token._timeElapsedQueryEnded) {
  15203. if (!token._timeElapsedQuery) {
  15204. return -1;
  15205. }
  15206. if (timerQuery.endQueryEXT) {
  15207. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15208. }
  15209. else {
  15210. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15211. }
  15212. token._timeElapsedQueryEnded = true;
  15213. }
  15214. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15215. var available = false;
  15216. if (token._endTimeQuery) {
  15217. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15218. }
  15219. else if (token._timeElapsedQuery) {
  15220. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15221. }
  15222. if (available && !disjoint) {
  15223. var result = 0;
  15224. if (this._caps.canUseTimestampForTimerQuery) {
  15225. if (!token._startTimeQuery || !token._endTimeQuery) {
  15226. return -1;
  15227. }
  15228. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15229. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15230. result = timeEnd - timeStart;
  15231. this._deleteTimeQuery(token._startTimeQuery);
  15232. this._deleteTimeQuery(token._endTimeQuery);
  15233. token._startTimeQuery = null;
  15234. token._endTimeQuery = null;
  15235. }
  15236. else {
  15237. if (!token._timeElapsedQuery) {
  15238. return -1;
  15239. }
  15240. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15241. this._deleteTimeQuery(token._timeElapsedQuery);
  15242. token._timeElapsedQuery = null;
  15243. token._timeElapsedQueryEnded = false;
  15244. this._currentNonTimestampToken = null;
  15245. }
  15246. return result;
  15247. }
  15248. return -1;
  15249. };
  15250. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15251. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15252. };
  15253. // Transform feedback
  15254. Engine.prototype.createTransformFeedback = function () {
  15255. return this._gl.createTransformFeedback();
  15256. };
  15257. Engine.prototype.deleteTransformFeedback = function (value) {
  15258. this._gl.deleteTransformFeedback(value);
  15259. };
  15260. Engine.prototype.bindTransformFeedback = function (value) {
  15261. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15262. };
  15263. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15264. if (usePoints === void 0) { usePoints = true; }
  15265. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15266. };
  15267. Engine.prototype.endTransformFeedback = function () {
  15268. this._gl.endTransformFeedback();
  15269. };
  15270. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15271. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15272. };
  15273. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15274. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15275. };
  15276. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15277. var _this = this;
  15278. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15279. this._activeRequests.push(request);
  15280. request.onCompleteObservable.add(function (request) {
  15281. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15282. });
  15283. return request;
  15284. };
  15285. /** @ignore */
  15286. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15287. var _this = this;
  15288. return new Promise(function (resolve, reject) {
  15289. _this._loadFile(url, function (data) {
  15290. resolve(data);
  15291. }, undefined, database, useArrayBuffer, function (request, exception) {
  15292. reject(exception);
  15293. });
  15294. });
  15295. };
  15296. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15297. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15298. var onload = function (data) {
  15299. loadedFiles[index] = data;
  15300. loadedFiles._internalCount++;
  15301. if (loadedFiles._internalCount === 6) {
  15302. onfinish(loadedFiles);
  15303. }
  15304. };
  15305. var onerror = function (request, exception) {
  15306. if (onErrorCallBack && request) {
  15307. onErrorCallBack(request.status + " " + request.statusText, exception);
  15308. }
  15309. };
  15310. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15311. };
  15312. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15313. if (onError === void 0) { onError = null; }
  15314. var loadedFiles = [];
  15315. loadedFiles._internalCount = 0;
  15316. for (var index = 0; index < 6; index++) {
  15317. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15318. }
  15319. };
  15320. // Statics
  15321. Engine.isSupported = function () {
  15322. try {
  15323. var tempcanvas = document.createElement("canvas");
  15324. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15325. return gl != null && !!window.WebGLRenderingContext;
  15326. }
  15327. catch (e) {
  15328. return false;
  15329. }
  15330. };
  15331. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15332. Engine.ExceptionList = [
  15333. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15334. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15335. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15336. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15337. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15338. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15339. ];
  15340. Engine.Instances = new Array();
  15341. // Const statics
  15342. Engine._ALPHA_DISABLE = 0;
  15343. Engine._ALPHA_ADD = 1;
  15344. Engine._ALPHA_COMBINE = 2;
  15345. Engine._ALPHA_SUBTRACT = 3;
  15346. Engine._ALPHA_MULTIPLY = 4;
  15347. Engine._ALPHA_MAXIMIZED = 5;
  15348. Engine._ALPHA_ONEONE = 6;
  15349. Engine._ALPHA_PREMULTIPLIED = 7;
  15350. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15351. Engine._ALPHA_INTERPOLATE = 9;
  15352. Engine._ALPHA_SCREENMODE = 10;
  15353. Engine._DELAYLOADSTATE_NONE = 0;
  15354. Engine._DELAYLOADSTATE_LOADED = 1;
  15355. Engine._DELAYLOADSTATE_LOADING = 2;
  15356. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15357. Engine._TEXTUREFORMAT_ALPHA = 0;
  15358. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15359. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15360. Engine._TEXTUREFORMAT_RGB = 4;
  15361. Engine._TEXTUREFORMAT_RGBA = 5;
  15362. Engine._TEXTUREFORMAT_R32F = 6;
  15363. Engine._TEXTUREFORMAT_RG32F = 7;
  15364. Engine._TEXTUREFORMAT_RGB32F = 8;
  15365. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15366. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15367. Engine._TEXTURETYPE_FLOAT = 1;
  15368. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15369. // Depht or Stencil test Constants.
  15370. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15371. 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.
  15372. 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.
  15373. 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.
  15374. 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.
  15375. 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.
  15376. 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.
  15377. 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.
  15378. // Stencil Actions Constants.
  15379. Engine._KEEP = 0x1E00;
  15380. Engine._REPLACE = 0x1E01;
  15381. Engine._INCR = 0x1E02;
  15382. Engine._DECR = 0x1E03;
  15383. Engine._INVERT = 0x150A;
  15384. Engine._INCR_WRAP = 0x8507;
  15385. Engine._DECR_WRAP = 0x8508;
  15386. // Texture rescaling mode
  15387. Engine._SCALEMODE_FLOOR = 1;
  15388. Engine._SCALEMODE_NEAREST = 2;
  15389. Engine._SCALEMODE_CEILING = 3;
  15390. // Updatable statics so stick with vars here
  15391. Engine.CollisionsEpsilon = 0.001;
  15392. Engine.CodeRepository = "src/";
  15393. Engine.ShadersRepository = "src/Shaders/";
  15394. return Engine;
  15395. }());
  15396. BABYLON.Engine = Engine;
  15397. })(BABYLON || (BABYLON = {}));
  15398. //# sourceMappingURL=babylon.engine.js.map
  15399. var BABYLON;
  15400. (function (BABYLON) {
  15401. /**
  15402. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15403. */
  15404. var Node = /** @class */ (function () {
  15405. /**
  15406. * Creates a new Node
  15407. * @param {string} name - the name and id to be given to this node
  15408. * @param {BABYLON.Scene} the scene this node will be added to
  15409. */
  15410. function Node(name, scene) {
  15411. if (scene === void 0) { scene = null; }
  15412. /**
  15413. * Gets or sets a string used to store user defined state for the node
  15414. */
  15415. this.state = "";
  15416. /**
  15417. * Gets or sets an object used to store user defined information for the node
  15418. */
  15419. this.metadata = null;
  15420. /**
  15421. * Gets or sets a boolean used to define if the node must be serialized
  15422. */
  15423. this.doNotSerialize = false;
  15424. /** @ignore */
  15425. this._isDisposed = false;
  15426. /**
  15427. * Gets a list of {BABYLON.Animation} associated with the node
  15428. */
  15429. this.animations = new Array();
  15430. this._ranges = {};
  15431. this._isEnabled = true;
  15432. this._isReady = true;
  15433. /** @ignore */
  15434. this._currentRenderId = -1;
  15435. this._parentRenderId = -1;
  15436. this._animationPropertiesOverride = null;
  15437. /**
  15438. * An event triggered when the mesh is disposed
  15439. * @type {BABYLON.Observable}
  15440. */
  15441. this.onDisposeObservable = new BABYLON.Observable();
  15442. // Behaviors
  15443. this._behaviors = new Array();
  15444. this.name = name;
  15445. this.id = name;
  15446. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15447. this.uniqueId = this._scene.getUniqueId();
  15448. this._initCache();
  15449. }
  15450. /**
  15451. * Gets a boolean indicating if the node has been disposed
  15452. * @returns true if the node was disposed
  15453. */
  15454. Node.prototype.isDisposed = function () {
  15455. return this._isDisposed;
  15456. };
  15457. Object.defineProperty(Node.prototype, "parent", {
  15458. get: function () {
  15459. return this._parentNode;
  15460. },
  15461. /**
  15462. * Gets or sets the parent of the node
  15463. */
  15464. set: function (parent) {
  15465. if (this._parentNode === parent) {
  15466. return;
  15467. }
  15468. // Remove self from list of children of parent
  15469. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15470. var index = this._parentNode._children.indexOf(this);
  15471. if (index !== -1) {
  15472. this._parentNode._children.splice(index, 1);
  15473. }
  15474. }
  15475. // Store new parent
  15476. this._parentNode = parent;
  15477. // Add as child to new parent
  15478. if (this._parentNode) {
  15479. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15480. this._parentNode._children = new Array();
  15481. }
  15482. this._parentNode._children.push(this);
  15483. }
  15484. },
  15485. enumerable: true,
  15486. configurable: true
  15487. });
  15488. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15489. /**
  15490. * Gets or sets the animation properties override
  15491. */
  15492. get: function () {
  15493. return this._animationPropertiesOverride;
  15494. },
  15495. set: function (value) {
  15496. this._animationPropertiesOverride = value;
  15497. },
  15498. enumerable: true,
  15499. configurable: true
  15500. });
  15501. /**
  15502. * Gets a string idenfifying the name of the class
  15503. * @returns "Node" string
  15504. */
  15505. Node.prototype.getClassName = function () {
  15506. return "Node";
  15507. };
  15508. Object.defineProperty(Node.prototype, "onDispose", {
  15509. /**
  15510. * Sets a callback that will be raised when the node will be disposed
  15511. */
  15512. set: function (callback) {
  15513. if (this._onDisposeObserver) {
  15514. this.onDisposeObservable.remove(this._onDisposeObserver);
  15515. }
  15516. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15517. },
  15518. enumerable: true,
  15519. configurable: true
  15520. });
  15521. /**
  15522. * Gets the scene of the node
  15523. * @returns a {BABYLON.Scene}
  15524. */
  15525. Node.prototype.getScene = function () {
  15526. return this._scene;
  15527. };
  15528. /**
  15529. * Gets the engine of the node
  15530. * @returns a {BABYLON.Engine}
  15531. */
  15532. Node.prototype.getEngine = function () {
  15533. return this._scene.getEngine();
  15534. };
  15535. /**
  15536. * Attach a behavior to the node
  15537. * @see http://doc.babylonjs.com/features/behaviour
  15538. * @param behavior defines the behavior to attach
  15539. * @returns the current Node
  15540. */
  15541. Node.prototype.addBehavior = function (behavior) {
  15542. var _this = this;
  15543. var index = this._behaviors.indexOf(behavior);
  15544. if (index !== -1) {
  15545. return this;
  15546. }
  15547. behavior.init();
  15548. if (this._scene.isLoading) {
  15549. // We defer the attach when the scene will be loaded
  15550. var observer = this._scene.onDataLoadedObservable.add(function () {
  15551. behavior.attach(_this);
  15552. setTimeout(function () {
  15553. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15554. _this._scene.onDataLoadedObservable.remove(observer);
  15555. }, 0);
  15556. });
  15557. }
  15558. else {
  15559. behavior.attach(this);
  15560. }
  15561. this._behaviors.push(behavior);
  15562. return this;
  15563. };
  15564. /**
  15565. * Remove an attached behavior
  15566. * @see http://doc.babylonjs.com/features/behaviour
  15567. * @param behavior defines the behavior to attach
  15568. * @returns the current Node
  15569. */
  15570. Node.prototype.removeBehavior = function (behavior) {
  15571. var index = this._behaviors.indexOf(behavior);
  15572. if (index === -1) {
  15573. return this;
  15574. }
  15575. this._behaviors[index].detach();
  15576. this._behaviors.splice(index, 1);
  15577. return this;
  15578. };
  15579. Object.defineProperty(Node.prototype, "behaviors", {
  15580. /**
  15581. * Gets the list of attached behaviors
  15582. * @see http://doc.babylonjs.com/features/behaviour
  15583. */
  15584. get: function () {
  15585. return this._behaviors;
  15586. },
  15587. enumerable: true,
  15588. configurable: true
  15589. });
  15590. /**
  15591. * Gets an attached behavior by name
  15592. * @param name defines the name of the behavior to look for
  15593. * @see http://doc.babylonjs.com/features/behaviour
  15594. * @returns null if behavior was not found else the requested behavior
  15595. */
  15596. Node.prototype.getBehaviorByName = function (name) {
  15597. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15598. var behavior = _a[_i];
  15599. if (behavior.name === name) {
  15600. return behavior;
  15601. }
  15602. }
  15603. return null;
  15604. };
  15605. /**
  15606. * Returns the world matrix of the node
  15607. * @returns a matrix containing the node's world matrix
  15608. */
  15609. Node.prototype.getWorldMatrix = function () {
  15610. return BABYLON.Matrix.Identity();
  15611. };
  15612. // override it in derived class if you add new variables to the cache
  15613. // and call the parent class method
  15614. /** @ignore */
  15615. Node.prototype._initCache = function () {
  15616. this._cache = {};
  15617. this._cache.parent = undefined;
  15618. };
  15619. /** @ignore */
  15620. Node.prototype.updateCache = function (force) {
  15621. if (!force && this.isSynchronized())
  15622. return;
  15623. this._cache.parent = this.parent;
  15624. this._updateCache();
  15625. };
  15626. // override it in derived class if you add new variables to the cache
  15627. // and call the parent class method if !ignoreParentClass
  15628. /** @ignore */
  15629. Node.prototype._updateCache = function (ignoreParentClass) {
  15630. };
  15631. // override it in derived class if you add new variables to the cache
  15632. /** @ignore */
  15633. Node.prototype._isSynchronized = function () {
  15634. return true;
  15635. };
  15636. /** @ignore */
  15637. Node.prototype._markSyncedWithParent = function () {
  15638. if (this.parent) {
  15639. this._parentRenderId = this.parent._currentRenderId;
  15640. }
  15641. };
  15642. /** @ignore */
  15643. Node.prototype.isSynchronizedWithParent = function () {
  15644. if (!this.parent) {
  15645. return true;
  15646. }
  15647. if (this._parentRenderId !== this.parent._currentRenderId) {
  15648. return false;
  15649. }
  15650. return this.parent.isSynchronized();
  15651. };
  15652. /** @ignore */
  15653. Node.prototype.isSynchronized = function (updateCache) {
  15654. var check = this.hasNewParent();
  15655. check = check || !this.isSynchronizedWithParent();
  15656. check = check || !this._isSynchronized();
  15657. if (updateCache)
  15658. this.updateCache(true);
  15659. return !check;
  15660. };
  15661. /** @ignore */
  15662. Node.prototype.hasNewParent = function (update) {
  15663. if (this._cache.parent === this.parent)
  15664. return false;
  15665. if (update)
  15666. this._cache.parent = this.parent;
  15667. return true;
  15668. };
  15669. /**
  15670. * Is this node ready to be used/rendered
  15671. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15672. * @return true if the node is ready
  15673. */
  15674. Node.prototype.isReady = function (completeCheck) {
  15675. if (completeCheck === void 0) { completeCheck = false; }
  15676. return this._isReady;
  15677. };
  15678. /**
  15679. * Is this node enabled?
  15680. * 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
  15681. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15682. * @return whether this node (and its parent) is enabled
  15683. * @see setEnabled
  15684. */
  15685. Node.prototype.isEnabled = function (checkAncestors) {
  15686. if (checkAncestors === void 0) { checkAncestors = true; }
  15687. if (checkAncestors === false) {
  15688. return this._isEnabled;
  15689. }
  15690. if (this._isEnabled === false) {
  15691. return false;
  15692. }
  15693. if (this.parent !== undefined && this.parent !== null) {
  15694. return this.parent.isEnabled(checkAncestors);
  15695. }
  15696. return true;
  15697. };
  15698. /**
  15699. * Set the enabled state of this node
  15700. * @param value defines the new enabled state
  15701. * @see isEnabled
  15702. */
  15703. Node.prototype.setEnabled = function (value) {
  15704. this._isEnabled = value;
  15705. };
  15706. /**
  15707. * Is this node a descendant of the given node?
  15708. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15709. * @param ancestor defines the parent node to inspect
  15710. * @see parent
  15711. * @returns a boolean indicating if this node is a descendant of the given node
  15712. */
  15713. Node.prototype.isDescendantOf = function (ancestor) {
  15714. if (this.parent) {
  15715. if (this.parent === ancestor) {
  15716. return true;
  15717. }
  15718. return this.parent.isDescendantOf(ancestor);
  15719. }
  15720. return false;
  15721. };
  15722. /** @ignore */
  15723. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15724. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15725. if (!this._children) {
  15726. return;
  15727. }
  15728. for (var index = 0; index < this._children.length; index++) {
  15729. var item = this._children[index];
  15730. if (!predicate || predicate(item)) {
  15731. results.push(item);
  15732. }
  15733. if (!directDescendantsOnly) {
  15734. item._getDescendants(results, false, predicate);
  15735. }
  15736. }
  15737. };
  15738. /**
  15739. * Will return all nodes that have this node as ascendant
  15740. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15741. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15742. * @return all children nodes of all types
  15743. */
  15744. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15745. var results = new Array();
  15746. this._getDescendants(results, directDescendantsOnly, predicate);
  15747. return results;
  15748. };
  15749. /**
  15750. * Get all child-meshes of this node
  15751. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15752. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15753. * @returns an array of {BABYLON.AbstractMesh}
  15754. */
  15755. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15756. var results = [];
  15757. this._getDescendants(results, directDescendantsOnly, function (node) {
  15758. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15759. });
  15760. return results;
  15761. };
  15762. /**
  15763. * Get all child-transformNodes of this node
  15764. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15765. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15766. * @returns an array of {BABYLON.TransformNode}
  15767. */
  15768. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15769. var results = [];
  15770. this._getDescendants(results, directDescendantsOnly, function (node) {
  15771. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15772. });
  15773. return results;
  15774. };
  15775. /**
  15776. * Get all direct children of this node
  15777. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15778. * @returns an array of {BABYLON.Node}
  15779. */
  15780. Node.prototype.getChildren = function (predicate) {
  15781. return this.getDescendants(true, predicate);
  15782. };
  15783. /** @ignore */
  15784. Node.prototype._setReady = function (state) {
  15785. if (state === this._isReady) {
  15786. return;
  15787. }
  15788. if (!state) {
  15789. this._isReady = false;
  15790. return;
  15791. }
  15792. this._isReady = true;
  15793. if (this.onReady) {
  15794. this.onReady(this);
  15795. }
  15796. };
  15797. /**
  15798. * Get an animation by name
  15799. * @param name defines the name of the animation to look for
  15800. * @returns null if not found else the requested animation
  15801. */
  15802. Node.prototype.getAnimationByName = function (name) {
  15803. for (var i = 0; i < this.animations.length; i++) {
  15804. var animation = this.animations[i];
  15805. if (animation.name === name) {
  15806. return animation;
  15807. }
  15808. }
  15809. return null;
  15810. };
  15811. /**
  15812. * Creates an animation range for this node
  15813. * @param name defines the name of the range
  15814. * @param from defines the starting key
  15815. * @param to defines the end key
  15816. */
  15817. Node.prototype.createAnimationRange = function (name, from, to) {
  15818. // check name not already in use
  15819. if (!this._ranges[name]) {
  15820. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15821. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15822. if (this.animations[i]) {
  15823. this.animations[i].createRange(name, from, to);
  15824. }
  15825. }
  15826. }
  15827. };
  15828. /**
  15829. * Delete a specific animation range
  15830. * @param name defines the name of the range to delete
  15831. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15832. */
  15833. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15834. if (deleteFrames === void 0) { deleteFrames = true; }
  15835. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15836. if (this.animations[i]) {
  15837. this.animations[i].deleteRange(name, deleteFrames);
  15838. }
  15839. }
  15840. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15841. };
  15842. /**
  15843. * Get an animation range by name
  15844. * @param name defines the name of the animation range to look for
  15845. * @returns null if not found else the requested animation range
  15846. */
  15847. Node.prototype.getAnimationRange = function (name) {
  15848. return this._ranges[name];
  15849. };
  15850. /**
  15851. * Will start the animation sequence
  15852. * @param name defines the range frames for animation sequence
  15853. * @param loop defines if the animation should loop (false by default)
  15854. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15855. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15856. * @returns the object created for this animation. If range does not exist, it will return null
  15857. */
  15858. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15859. var range = this.getAnimationRange(name);
  15860. if (!range) {
  15861. return null;
  15862. }
  15863. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15864. };
  15865. /**
  15866. * Serialize animation ranges into a JSON compatible object
  15867. * @returns serialization object
  15868. */
  15869. Node.prototype.serializeAnimationRanges = function () {
  15870. var serializationRanges = [];
  15871. for (var name in this._ranges) {
  15872. var localRange = this._ranges[name];
  15873. if (!localRange) {
  15874. continue;
  15875. }
  15876. var range = {};
  15877. range.name = name;
  15878. range.from = localRange.from;
  15879. range.to = localRange.to;
  15880. serializationRanges.push(range);
  15881. }
  15882. return serializationRanges;
  15883. };
  15884. /**
  15885. * Computes the world matrix of the node
  15886. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15887. * @returns the world matrix
  15888. */
  15889. Node.prototype.computeWorldMatrix = function (force) {
  15890. return BABYLON.Matrix.Identity();
  15891. };
  15892. /**
  15893. * Releases resources associated with this node.
  15894. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15895. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15896. */
  15897. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15898. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15899. if (!doNotRecurse) {
  15900. var nodes = this.getDescendants(true);
  15901. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15902. var node = nodes_1[_i];
  15903. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15904. }
  15905. }
  15906. else {
  15907. var transformNodes = this.getChildTransformNodes(true);
  15908. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15909. var transformNode = transformNodes_1[_a];
  15910. transformNode.parent = null;
  15911. transformNode.computeWorldMatrix(true);
  15912. }
  15913. }
  15914. this.parent = null;
  15915. // Callback
  15916. this.onDisposeObservable.notifyObservers(this);
  15917. this.onDisposeObservable.clear();
  15918. // Behaviors
  15919. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  15920. var behavior = _c[_b];
  15921. behavior.detach();
  15922. }
  15923. this._behaviors = [];
  15924. this._isDisposed = true;
  15925. };
  15926. /**
  15927. * Parse animation range data from a serialization object and store them into a given node
  15928. * @param node defines where to store the animation ranges
  15929. * @param parsedNode defines the serialization object to read data from
  15930. * @param scene defines the hosting scene
  15931. */
  15932. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15933. if (parsedNode.ranges) {
  15934. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15935. var data = parsedNode.ranges[index];
  15936. node.createAnimationRange(data.name, data.from, data.to);
  15937. }
  15938. }
  15939. };
  15940. __decorate([
  15941. BABYLON.serialize()
  15942. ], Node.prototype, "name", void 0);
  15943. __decorate([
  15944. BABYLON.serialize()
  15945. ], Node.prototype, "id", void 0);
  15946. __decorate([
  15947. BABYLON.serialize()
  15948. ], Node.prototype, "uniqueId", void 0);
  15949. __decorate([
  15950. BABYLON.serialize()
  15951. ], Node.prototype, "state", void 0);
  15952. __decorate([
  15953. BABYLON.serialize()
  15954. ], Node.prototype, "metadata", void 0);
  15955. return Node;
  15956. }());
  15957. BABYLON.Node = Node;
  15958. })(BABYLON || (BABYLON = {}));
  15959. //# sourceMappingURL=babylon.node.js.map
  15960. var BABYLON;
  15961. (function (BABYLON) {
  15962. var BoundingSphere = /** @class */ (function () {
  15963. function BoundingSphere(minimum, maximum) {
  15964. this.minimum = minimum;
  15965. this.maximum = maximum;
  15966. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15967. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15968. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15969. this.radius = distance * 0.5;
  15970. this.centerWorld = BABYLON.Vector3.Zero();
  15971. this._update(BABYLON.Matrix.Identity());
  15972. }
  15973. // Methods
  15974. BoundingSphere.prototype._update = function (world) {
  15975. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15976. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15977. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15978. };
  15979. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15980. for (var i = 0; i < 6; i++) {
  15981. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15982. return false;
  15983. }
  15984. return true;
  15985. };
  15986. BoundingSphere.prototype.intersectsPoint = function (point) {
  15987. var x = this.centerWorld.x - point.x;
  15988. var y = this.centerWorld.y - point.y;
  15989. var z = this.centerWorld.z - point.z;
  15990. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15991. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15992. return false;
  15993. return true;
  15994. };
  15995. // Statics
  15996. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15997. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15998. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15999. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16000. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16001. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16002. return false;
  16003. return true;
  16004. };
  16005. return BoundingSphere;
  16006. }());
  16007. BABYLON.BoundingSphere = BoundingSphere;
  16008. })(BABYLON || (BABYLON = {}));
  16009. //# sourceMappingURL=babylon.boundingSphere.js.map
  16010. var BABYLON;
  16011. (function (BABYLON) {
  16012. var BoundingBox = /** @class */ (function () {
  16013. function BoundingBox(minimum, maximum) {
  16014. this.minimum = minimum;
  16015. this.maximum = maximum;
  16016. this.vectors = new Array();
  16017. this.vectorsWorld = new Array();
  16018. // Bounding vectors
  16019. this.vectors.push(this.minimum.clone());
  16020. this.vectors.push(this.maximum.clone());
  16021. this.vectors.push(this.minimum.clone());
  16022. this.vectors[2].x = this.maximum.x;
  16023. this.vectors.push(this.minimum.clone());
  16024. this.vectors[3].y = this.maximum.y;
  16025. this.vectors.push(this.minimum.clone());
  16026. this.vectors[4].z = this.maximum.z;
  16027. this.vectors.push(this.maximum.clone());
  16028. this.vectors[5].z = this.minimum.z;
  16029. this.vectors.push(this.maximum.clone());
  16030. this.vectors[6].x = this.minimum.x;
  16031. this.vectors.push(this.maximum.clone());
  16032. this.vectors[7].y = this.minimum.y;
  16033. // OBB
  16034. this.center = this.maximum.add(this.minimum).scale(0.5);
  16035. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16036. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16037. // World
  16038. for (var index = 0; index < this.vectors.length; index++) {
  16039. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16040. }
  16041. this.minimumWorld = BABYLON.Vector3.Zero();
  16042. this.maximumWorld = BABYLON.Vector3.Zero();
  16043. this.centerWorld = BABYLON.Vector3.Zero();
  16044. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16045. this._update(BABYLON.Matrix.Identity());
  16046. }
  16047. // Methods
  16048. BoundingBox.prototype.getWorldMatrix = function () {
  16049. return this._worldMatrix;
  16050. };
  16051. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16052. this._worldMatrix.copyFrom(matrix);
  16053. return this;
  16054. };
  16055. BoundingBox.prototype._update = function (world) {
  16056. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16057. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16058. for (var index = 0; index < this.vectors.length; index++) {
  16059. var v = this.vectorsWorld[index];
  16060. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16061. if (v.x < this.minimumWorld.x)
  16062. this.minimumWorld.x = v.x;
  16063. if (v.y < this.minimumWorld.y)
  16064. this.minimumWorld.y = v.y;
  16065. if (v.z < this.minimumWorld.z)
  16066. this.minimumWorld.z = v.z;
  16067. if (v.x > this.maximumWorld.x)
  16068. this.maximumWorld.x = v.x;
  16069. if (v.y > this.maximumWorld.y)
  16070. this.maximumWorld.y = v.y;
  16071. if (v.z > this.maximumWorld.z)
  16072. this.maximumWorld.z = v.z;
  16073. }
  16074. // Extend
  16075. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16076. this.extendSizeWorld.scaleInPlace(0.5);
  16077. // OBB
  16078. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16079. this.centerWorld.scaleInPlace(0.5);
  16080. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16081. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16082. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16083. this._worldMatrix = world;
  16084. };
  16085. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16086. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16087. };
  16088. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16089. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16090. };
  16091. BoundingBox.prototype.intersectsPoint = function (point) {
  16092. var delta = -BABYLON.Epsilon;
  16093. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16094. return false;
  16095. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16096. return false;
  16097. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16098. return false;
  16099. return true;
  16100. };
  16101. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16102. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16103. };
  16104. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16105. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16106. return false;
  16107. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16108. return false;
  16109. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16110. return false;
  16111. return true;
  16112. };
  16113. // Statics
  16114. BoundingBox.Intersects = function (box0, box1) {
  16115. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16116. return false;
  16117. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16118. return false;
  16119. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16120. return false;
  16121. return true;
  16122. };
  16123. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16124. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16125. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16126. return (num <= (sphereRadius * sphereRadius));
  16127. };
  16128. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16129. for (var p = 0; p < 6; p++) {
  16130. for (var i = 0; i < 8; i++) {
  16131. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16132. return false;
  16133. }
  16134. }
  16135. }
  16136. return true;
  16137. };
  16138. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16139. for (var p = 0; p < 6; p++) {
  16140. var inCount = 8;
  16141. for (var i = 0; i < 8; i++) {
  16142. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16143. --inCount;
  16144. }
  16145. else {
  16146. break;
  16147. }
  16148. }
  16149. if (inCount === 0)
  16150. return false;
  16151. }
  16152. return true;
  16153. };
  16154. return BoundingBox;
  16155. }());
  16156. BABYLON.BoundingBox = BoundingBox;
  16157. })(BABYLON || (BABYLON = {}));
  16158. //# sourceMappingURL=babylon.boundingBox.js.map
  16159. var BABYLON;
  16160. (function (BABYLON) {
  16161. var computeBoxExtents = function (axis, box) {
  16162. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16163. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16164. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16165. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16166. var r = r0 + r1 + r2;
  16167. return {
  16168. min: p - r,
  16169. max: p + r
  16170. };
  16171. };
  16172. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16173. var axisOverlap = function (axis, box0, box1) {
  16174. var result0 = computeBoxExtents(axis, box0);
  16175. var result1 = computeBoxExtents(axis, box1);
  16176. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16177. };
  16178. var BoundingInfo = /** @class */ (function () {
  16179. function BoundingInfo(minimum, maximum) {
  16180. this.minimum = minimum;
  16181. this.maximum = maximum;
  16182. this._isLocked = false;
  16183. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16184. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16185. }
  16186. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16187. get: function () {
  16188. return this._isLocked;
  16189. },
  16190. set: function (value) {
  16191. this._isLocked = value;
  16192. },
  16193. enumerable: true,
  16194. configurable: true
  16195. });
  16196. // Methods
  16197. BoundingInfo.prototype.update = function (world) {
  16198. if (this._isLocked) {
  16199. return;
  16200. }
  16201. this.boundingBox._update(world);
  16202. this.boundingSphere._update(world);
  16203. };
  16204. /**
  16205. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16206. * @param center New center of the bounding info
  16207. * @param extend New extend of the bounding info
  16208. */
  16209. BoundingInfo.prototype.centerOn = function (center, extend) {
  16210. this.minimum = center.subtract(extend);
  16211. this.maximum = center.add(extend);
  16212. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16213. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16214. return this;
  16215. };
  16216. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16217. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16218. return false;
  16219. return this.boundingBox.isInFrustum(frustumPlanes);
  16220. };
  16221. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16222. /**
  16223. * Gets the world distance between the min and max points of the bounding box
  16224. */
  16225. get: function () {
  16226. var boundingBox = this.boundingBox;
  16227. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16228. return size.length();
  16229. },
  16230. enumerable: true,
  16231. configurable: true
  16232. });
  16233. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16234. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16235. };
  16236. BoundingInfo.prototype._checkCollision = function (collider) {
  16237. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16238. };
  16239. BoundingInfo.prototype.intersectsPoint = function (point) {
  16240. if (!this.boundingSphere.centerWorld) {
  16241. return false;
  16242. }
  16243. if (!this.boundingSphere.intersectsPoint(point)) {
  16244. return false;
  16245. }
  16246. if (!this.boundingBox.intersectsPoint(point)) {
  16247. return false;
  16248. }
  16249. return true;
  16250. };
  16251. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16252. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16253. return false;
  16254. }
  16255. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16256. return false;
  16257. }
  16258. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16259. return false;
  16260. }
  16261. if (!precise) {
  16262. return true;
  16263. }
  16264. var box0 = this.boundingBox;
  16265. var box1 = boundingInfo.boundingBox;
  16266. if (!axisOverlap(box0.directions[0], box0, box1))
  16267. return false;
  16268. if (!axisOverlap(box0.directions[1], box0, box1))
  16269. return false;
  16270. if (!axisOverlap(box0.directions[2], box0, box1))
  16271. return false;
  16272. if (!axisOverlap(box1.directions[0], box0, box1))
  16273. return false;
  16274. if (!axisOverlap(box1.directions[1], box0, box1))
  16275. return false;
  16276. if (!axisOverlap(box1.directions[2], box0, box1))
  16277. return false;
  16278. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16279. return false;
  16280. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16281. return false;
  16282. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16283. return false;
  16284. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16285. return false;
  16286. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16287. return false;
  16288. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16289. return false;
  16290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16291. return false;
  16292. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16293. return false;
  16294. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16295. return false;
  16296. return true;
  16297. };
  16298. return BoundingInfo;
  16299. }());
  16300. BABYLON.BoundingInfo = BoundingInfo;
  16301. })(BABYLON || (BABYLON = {}));
  16302. //# sourceMappingURL=babylon.boundingInfo.js.map
  16303. var BABYLON;
  16304. (function (BABYLON) {
  16305. var TransformNode = /** @class */ (function (_super) {
  16306. __extends(TransformNode, _super);
  16307. function TransformNode(name, scene, isPure) {
  16308. if (scene === void 0) { scene = null; }
  16309. if (isPure === void 0) { isPure = true; }
  16310. var _this = _super.call(this, name, scene) || this;
  16311. // Properties
  16312. _this._rotation = BABYLON.Vector3.Zero();
  16313. _this._scaling = BABYLON.Vector3.One();
  16314. _this._isDirty = false;
  16315. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16316. _this.scalingDeterminant = 1;
  16317. _this.infiniteDistance = false;
  16318. _this.position = BABYLON.Vector3.Zero();
  16319. _this._localWorld = BABYLON.Matrix.Zero();
  16320. _this._worldMatrix = BABYLON.Matrix.Zero();
  16321. _this._worldMatrixDeterminant = 0;
  16322. _this._absolutePosition = BABYLON.Vector3.Zero();
  16323. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16324. _this._postMultiplyPivotMatrix = false;
  16325. _this._isWorldMatrixFrozen = false;
  16326. /**
  16327. * An event triggered after the world matrix is updated
  16328. * @type {BABYLON.Observable}
  16329. */
  16330. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16331. _this._nonUniformScaling = false;
  16332. if (isPure) {
  16333. _this.getScene().addTransformNode(_this);
  16334. }
  16335. return _this;
  16336. }
  16337. /**
  16338. * Gets a string idenfifying the name of the class
  16339. * @returns "TransformNode" string
  16340. */
  16341. TransformNode.prototype.getClassName = function () {
  16342. return "TransformNode";
  16343. };
  16344. Object.defineProperty(TransformNode.prototype, "rotation", {
  16345. /**
  16346. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16347. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16348. * Default : (0.0, 0.0, 0.0)
  16349. */
  16350. get: function () {
  16351. return this._rotation;
  16352. },
  16353. set: function (newRotation) {
  16354. this._rotation = newRotation;
  16355. },
  16356. enumerable: true,
  16357. configurable: true
  16358. });
  16359. Object.defineProperty(TransformNode.prototype, "scaling", {
  16360. /**
  16361. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16362. * Default : (1.0, 1.0, 1.0)
  16363. */
  16364. get: function () {
  16365. return this._scaling;
  16366. },
  16367. /**
  16368. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16369. * Default : (1.0, 1.0, 1.0)
  16370. */
  16371. set: function (newScaling) {
  16372. this._scaling = newScaling;
  16373. },
  16374. enumerable: true,
  16375. configurable: true
  16376. });
  16377. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16378. /**
  16379. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16380. * It's null by default.
  16381. * 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)
  16382. */
  16383. get: function () {
  16384. return this._rotationQuaternion;
  16385. },
  16386. set: function (quaternion) {
  16387. this._rotationQuaternion = quaternion;
  16388. //reset the rotation vector.
  16389. if (quaternion && this.rotation.length()) {
  16390. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16391. }
  16392. },
  16393. enumerable: true,
  16394. configurable: true
  16395. });
  16396. /**
  16397. * Returns the latest update of the World matrix
  16398. * Returns a Matrix.
  16399. */
  16400. TransformNode.prototype.getWorldMatrix = function () {
  16401. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16402. this.computeWorldMatrix();
  16403. }
  16404. return this._worldMatrix;
  16405. };
  16406. /**
  16407. * Returns the latest update of the World matrix determinant.
  16408. */
  16409. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16410. return this._worldMatrixDeterminant;
  16411. };
  16412. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16413. /**
  16414. * Returns directly the latest state of the mesh World matrix.
  16415. * A Matrix is returned.
  16416. */
  16417. get: function () {
  16418. return this._worldMatrix;
  16419. },
  16420. enumerable: true,
  16421. configurable: true
  16422. });
  16423. /**
  16424. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16425. * Returns the AbstractMesh.
  16426. */
  16427. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16428. this._poseMatrix.copyFrom(matrix);
  16429. return this;
  16430. };
  16431. /**
  16432. * Returns the mesh Pose matrix.
  16433. * Returned object : Matrix
  16434. */
  16435. TransformNode.prototype.getPoseMatrix = function () {
  16436. return this._poseMatrix;
  16437. };
  16438. TransformNode.prototype._isSynchronized = function () {
  16439. if (this._isDirty) {
  16440. return false;
  16441. }
  16442. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16443. return false;
  16444. if (this._cache.pivotMatrixUpdated) {
  16445. return false;
  16446. }
  16447. if (this.infiniteDistance) {
  16448. return false;
  16449. }
  16450. if (!this._cache.position.equals(this.position))
  16451. return false;
  16452. if (this.rotationQuaternion) {
  16453. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16454. return false;
  16455. }
  16456. if (!this._cache.rotation.equals(this.rotation))
  16457. return false;
  16458. if (!this._cache.scaling.equals(this.scaling))
  16459. return false;
  16460. return true;
  16461. };
  16462. TransformNode.prototype._initCache = function () {
  16463. _super.prototype._initCache.call(this);
  16464. this._cache.localMatrixUpdated = false;
  16465. this._cache.position = BABYLON.Vector3.Zero();
  16466. this._cache.scaling = BABYLON.Vector3.Zero();
  16467. this._cache.rotation = BABYLON.Vector3.Zero();
  16468. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16469. this._cache.billboardMode = -1;
  16470. };
  16471. TransformNode.prototype.markAsDirty = function (property) {
  16472. if (property === "rotation") {
  16473. this.rotationQuaternion = null;
  16474. }
  16475. this._currentRenderId = Number.MAX_VALUE;
  16476. this._isDirty = true;
  16477. return this;
  16478. };
  16479. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16480. /**
  16481. * Returns the current mesh absolute position.
  16482. * Retuns a Vector3.
  16483. */
  16484. get: function () {
  16485. return this._absolutePosition;
  16486. },
  16487. enumerable: true,
  16488. configurable: true
  16489. });
  16490. /**
  16491. * Sets a new matrix to apply before all other transformation
  16492. * @param matrix defines the transform matrix
  16493. * @returns the current TransformNode
  16494. */
  16495. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16496. return this.setPivotMatrix(matrix, false);
  16497. };
  16498. /**
  16499. * Sets a new pivot matrix to the current node
  16500. * @param matrix defines the new pivot matrix to use
  16501. * @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
  16502. * @returns the current TransformNode
  16503. */
  16504. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16505. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16506. this._pivotMatrix = matrix.clone();
  16507. this._cache.pivotMatrixUpdated = true;
  16508. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16509. if (this._postMultiplyPivotMatrix) {
  16510. if (!this._pivotMatrixInverse) {
  16511. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16512. }
  16513. else {
  16514. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16515. }
  16516. }
  16517. return this;
  16518. };
  16519. /**
  16520. * Returns the mesh pivot matrix.
  16521. * Default : Identity.
  16522. * A Matrix is returned.
  16523. */
  16524. TransformNode.prototype.getPivotMatrix = function () {
  16525. return this._pivotMatrix;
  16526. };
  16527. /**
  16528. * Prevents the World matrix to be computed any longer.
  16529. * Returns the AbstractMesh.
  16530. */
  16531. TransformNode.prototype.freezeWorldMatrix = function () {
  16532. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16533. this.computeWorldMatrix(true);
  16534. this._isWorldMatrixFrozen = true;
  16535. return this;
  16536. };
  16537. /**
  16538. * Allows back the World matrix computation.
  16539. * Returns the AbstractMesh.
  16540. */
  16541. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16542. this._isWorldMatrixFrozen = false;
  16543. this.computeWorldMatrix(true);
  16544. return this;
  16545. };
  16546. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16547. /**
  16548. * True if the World matrix has been frozen.
  16549. * Returns a boolean.
  16550. */
  16551. get: function () {
  16552. return this._isWorldMatrixFrozen;
  16553. },
  16554. enumerable: true,
  16555. configurable: true
  16556. });
  16557. /**
  16558. * Retuns the mesh absolute position in the World.
  16559. * Returns a Vector3.
  16560. */
  16561. TransformNode.prototype.getAbsolutePosition = function () {
  16562. this.computeWorldMatrix();
  16563. return this._absolutePosition;
  16564. };
  16565. /**
  16566. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16567. * Returns the AbstractMesh.
  16568. */
  16569. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16570. if (!absolutePosition) {
  16571. return this;
  16572. }
  16573. var absolutePositionX;
  16574. var absolutePositionY;
  16575. var absolutePositionZ;
  16576. if (absolutePosition.x === undefined) {
  16577. if (arguments.length < 3) {
  16578. return this;
  16579. }
  16580. absolutePositionX = arguments[0];
  16581. absolutePositionY = arguments[1];
  16582. absolutePositionZ = arguments[2];
  16583. }
  16584. else {
  16585. absolutePositionX = absolutePosition.x;
  16586. absolutePositionY = absolutePosition.y;
  16587. absolutePositionZ = absolutePosition.z;
  16588. }
  16589. if (this.parent) {
  16590. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16591. invertParentWorldMatrix.invert();
  16592. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16593. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16594. }
  16595. else {
  16596. this.position.x = absolutePositionX;
  16597. this.position.y = absolutePositionY;
  16598. this.position.z = absolutePositionZ;
  16599. }
  16600. return this;
  16601. };
  16602. /**
  16603. * Sets the mesh position in its local space.
  16604. * Returns the AbstractMesh.
  16605. */
  16606. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16607. this.computeWorldMatrix();
  16608. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16609. return this;
  16610. };
  16611. /**
  16612. * Returns the mesh position in the local space from the current World matrix values.
  16613. * Returns a new Vector3.
  16614. */
  16615. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16616. this.computeWorldMatrix();
  16617. var invLocalWorldMatrix = this._localWorld.clone();
  16618. invLocalWorldMatrix.invert();
  16619. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16620. };
  16621. /**
  16622. * Translates the mesh along the passed Vector3 in its local space.
  16623. * Returns the AbstractMesh.
  16624. */
  16625. TransformNode.prototype.locallyTranslate = function (vector3) {
  16626. this.computeWorldMatrix(true);
  16627. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16628. return this;
  16629. };
  16630. /**
  16631. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16632. * @param targetPoint the position (must be in same space as current mesh) to look at
  16633. * @param yawCor optional yaw (y-axis) correction in radians
  16634. * @param pitchCor optional pitch (x-axis) correction in radians
  16635. * @param rollCor optional roll (z-axis) correction in radians
  16636. * @param space the choosen space of the target
  16637. * @returns the TransformNode.
  16638. */
  16639. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16640. if (yawCor === void 0) { yawCor = 0; }
  16641. if (pitchCor === void 0) { pitchCor = 0; }
  16642. if (rollCor === void 0) { rollCor = 0; }
  16643. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16644. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16645. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16646. targetPoint.subtractToRef(pos, dv);
  16647. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16648. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16649. var pitch = Math.atan2(dv.y, len);
  16650. if (this.rotationQuaternion) {
  16651. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16652. }
  16653. else {
  16654. this.rotation.x = pitch + pitchCor;
  16655. this.rotation.y = yaw + yawCor;
  16656. this.rotation.z = rollCor;
  16657. }
  16658. return this;
  16659. };
  16660. /**
  16661. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16662. * This Vector3 is expressed in the World space.
  16663. */
  16664. TransformNode.prototype.getDirection = function (localAxis) {
  16665. var result = BABYLON.Vector3.Zero();
  16666. this.getDirectionToRef(localAxis, result);
  16667. return result;
  16668. };
  16669. /**
  16670. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16671. * localAxis is expressed in the mesh local space.
  16672. * result is computed in the Wordl space from the mesh World matrix.
  16673. * Returns the AbstractMesh.
  16674. */
  16675. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16676. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16677. return this;
  16678. };
  16679. /**
  16680. * Sets a new pivot point to the current node
  16681. * @param point defines the new pivot point to use
  16682. * @param space defines if the point is in world or local space (local by default)
  16683. * @returns the current TransformNode
  16684. */
  16685. TransformNode.prototype.setPivotPoint = function (point, space) {
  16686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16687. if (this.getScene().getRenderId() == 0) {
  16688. this.computeWorldMatrix(true);
  16689. }
  16690. var wm = this.getWorldMatrix();
  16691. if (space == BABYLON.Space.WORLD) {
  16692. var tmat = BABYLON.Tmp.Matrix[0];
  16693. wm.invertToRef(tmat);
  16694. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16695. }
  16696. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16697. };
  16698. /**
  16699. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16700. */
  16701. TransformNode.prototype.getPivotPoint = function () {
  16702. var point = BABYLON.Vector3.Zero();
  16703. this.getPivotPointToRef(point);
  16704. return point;
  16705. };
  16706. /**
  16707. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16708. * Returns the AbstractMesh.
  16709. */
  16710. TransformNode.prototype.getPivotPointToRef = function (result) {
  16711. result.x = -this._pivotMatrix.m[12];
  16712. result.y = -this._pivotMatrix.m[13];
  16713. result.z = -this._pivotMatrix.m[14];
  16714. return this;
  16715. };
  16716. /**
  16717. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16718. */
  16719. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16720. var point = BABYLON.Vector3.Zero();
  16721. this.getAbsolutePivotPointToRef(point);
  16722. return point;
  16723. };
  16724. /**
  16725. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16726. * Returns the AbstractMesh.
  16727. */
  16728. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16729. result.x = this._pivotMatrix.m[12];
  16730. result.y = this._pivotMatrix.m[13];
  16731. result.z = this._pivotMatrix.m[14];
  16732. this.getPivotPointToRef(result);
  16733. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16734. return this;
  16735. };
  16736. /**
  16737. * Defines the passed node as the parent of the current node.
  16738. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16739. * Returns the TransformNode.
  16740. */
  16741. TransformNode.prototype.setParent = function (node) {
  16742. if (node === null) {
  16743. var rotation = BABYLON.Tmp.Quaternion[0];
  16744. var position = BABYLON.Tmp.Vector3[0];
  16745. var scale = BABYLON.Tmp.Vector3[1];
  16746. if (this.parent && this.parent.computeWorldMatrix) {
  16747. this.parent.computeWorldMatrix(true);
  16748. }
  16749. this.computeWorldMatrix(true);
  16750. this.getWorldMatrix().decompose(scale, rotation, position);
  16751. if (this.rotationQuaternion) {
  16752. this.rotationQuaternion.copyFrom(rotation);
  16753. }
  16754. else {
  16755. rotation.toEulerAnglesToRef(this.rotation);
  16756. }
  16757. this.scaling.x = scale.x;
  16758. this.scaling.y = scale.y;
  16759. this.scaling.z = scale.z;
  16760. this.position.x = position.x;
  16761. this.position.y = position.y;
  16762. this.position.z = position.z;
  16763. }
  16764. else {
  16765. var rotation = BABYLON.Tmp.Quaternion[0];
  16766. var position = BABYLON.Tmp.Vector3[0];
  16767. var scale = BABYLON.Tmp.Vector3[1];
  16768. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16769. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16770. this.computeWorldMatrix(true);
  16771. node.computeWorldMatrix(true);
  16772. node.getWorldMatrix().invertToRef(invParentMatrix);
  16773. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16774. diffMatrix.decompose(scale, rotation, position);
  16775. if (this.rotationQuaternion) {
  16776. this.rotationQuaternion.copyFrom(rotation);
  16777. }
  16778. else {
  16779. rotation.toEulerAnglesToRef(this.rotation);
  16780. }
  16781. this.position.x = position.x;
  16782. this.position.y = position.y;
  16783. this.position.z = position.z;
  16784. this.scaling.x = scale.x;
  16785. this.scaling.y = scale.y;
  16786. this.scaling.z = scale.z;
  16787. }
  16788. this.parent = node;
  16789. return this;
  16790. };
  16791. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16792. get: function () {
  16793. return this._nonUniformScaling;
  16794. },
  16795. enumerable: true,
  16796. configurable: true
  16797. });
  16798. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16799. if (this._nonUniformScaling === value) {
  16800. return false;
  16801. }
  16802. this._nonUniformScaling = true;
  16803. return true;
  16804. };
  16805. /**
  16806. * Attach the current TransformNode to another TransformNode associated with a bone
  16807. * @param bone Bone affecting the TransformNode
  16808. * @param affectedTransformNode TransformNode associated with the bone
  16809. */
  16810. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16811. this._transformToBoneReferal = affectedTransformNode;
  16812. this.parent = bone;
  16813. if (bone.getWorldMatrix().determinant() < 0) {
  16814. this.scalingDeterminant *= -1;
  16815. }
  16816. return this;
  16817. };
  16818. TransformNode.prototype.detachFromBone = function () {
  16819. if (!this.parent) {
  16820. return this;
  16821. }
  16822. if (this.parent.getWorldMatrix().determinant() < 0) {
  16823. this.scalingDeterminant *= -1;
  16824. }
  16825. this._transformToBoneReferal = null;
  16826. this.parent = null;
  16827. return this;
  16828. };
  16829. /**
  16830. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16831. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16832. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16833. * The passed axis is also normalized.
  16834. * Returns the AbstractMesh.
  16835. */
  16836. TransformNode.prototype.rotate = function (axis, amount, space) {
  16837. axis.normalize();
  16838. if (!this.rotationQuaternion) {
  16839. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16840. this.rotation = BABYLON.Vector3.Zero();
  16841. }
  16842. var rotationQuaternion;
  16843. if (!space || space === BABYLON.Space.LOCAL) {
  16844. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16845. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16846. }
  16847. else {
  16848. if (this.parent) {
  16849. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16850. invertParentWorldMatrix.invert();
  16851. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16852. }
  16853. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16854. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16855. }
  16856. return this;
  16857. };
  16858. /**
  16859. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16860. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16861. * The passed axis is also normalized.
  16862. * Returns the AbstractMesh.
  16863. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16864. */
  16865. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16866. axis.normalize();
  16867. if (!this.rotationQuaternion) {
  16868. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16869. this.rotation.copyFromFloats(0, 0, 0);
  16870. }
  16871. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16872. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16873. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16874. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16875. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16876. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16877. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16878. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16879. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16880. return this;
  16881. };
  16882. /**
  16883. * Translates the mesh along the axis vector for the passed distance in the given space.
  16884. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16885. * Returns the AbstractMesh.
  16886. */
  16887. TransformNode.prototype.translate = function (axis, distance, space) {
  16888. var displacementVector = axis.scale(distance);
  16889. if (!space || space === BABYLON.Space.LOCAL) {
  16890. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16891. this.setPositionWithLocalVector(tempV3);
  16892. }
  16893. else {
  16894. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16895. }
  16896. return this;
  16897. };
  16898. /**
  16899. * Adds a rotation step to the mesh current rotation.
  16900. * x, y, z are Euler angles expressed in radians.
  16901. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16902. * This means this rotation is made in the mesh local space only.
  16903. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16904. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16905. * ```javascript
  16906. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16907. * ```
  16908. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16909. * 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.
  16910. * Returns the AbstractMesh.
  16911. */
  16912. TransformNode.prototype.addRotation = function (x, y, z) {
  16913. var rotationQuaternion;
  16914. if (this.rotationQuaternion) {
  16915. rotationQuaternion = this.rotationQuaternion;
  16916. }
  16917. else {
  16918. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16919. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16920. }
  16921. var accumulation = BABYLON.Tmp.Quaternion[0];
  16922. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16923. rotationQuaternion.multiplyInPlace(accumulation);
  16924. if (!this.rotationQuaternion) {
  16925. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16926. }
  16927. return this;
  16928. };
  16929. /**
  16930. * Computes the mesh World matrix and returns it.
  16931. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16932. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16933. * If the parameter `force`is set to `true`, the actual computation is done.
  16934. * Returns the mesh World Matrix.
  16935. */
  16936. TransformNode.prototype.computeWorldMatrix = function (force) {
  16937. if (this._isWorldMatrixFrozen) {
  16938. return this._worldMatrix;
  16939. }
  16940. if (!force && this.isSynchronized(true)) {
  16941. return this._worldMatrix;
  16942. }
  16943. this._cache.position.copyFrom(this.position);
  16944. this._cache.scaling.copyFrom(this.scaling);
  16945. this._cache.pivotMatrixUpdated = false;
  16946. this._cache.billboardMode = this.billboardMode;
  16947. this._currentRenderId = this.getScene().getRenderId();
  16948. this._isDirty = false;
  16949. // Scaling
  16950. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16951. // Rotation
  16952. //rotate, if quaternion is set and rotation was used
  16953. if (this.rotationQuaternion) {
  16954. var len = this.rotation.length();
  16955. if (len) {
  16956. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16957. this.rotation.copyFromFloats(0, 0, 0);
  16958. }
  16959. }
  16960. if (this.rotationQuaternion) {
  16961. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16962. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16963. }
  16964. else {
  16965. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16966. this._cache.rotation.copyFrom(this.rotation);
  16967. }
  16968. // Translation
  16969. var camera = this.getScene().activeCamera;
  16970. if (this.infiniteDistance && !this.parent && camera) {
  16971. var cameraWorldMatrix = camera.getWorldMatrix();
  16972. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16973. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16974. }
  16975. else {
  16976. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16977. }
  16978. // Composing transformations
  16979. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16980. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16981. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16982. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16983. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16984. // Need to decompose each rotation here
  16985. var currentPosition = BABYLON.Tmp.Vector3[3];
  16986. if (this.parent && this.parent.getWorldMatrix) {
  16987. if (this._transformToBoneReferal) {
  16988. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16989. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16990. }
  16991. else {
  16992. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16993. }
  16994. }
  16995. else {
  16996. currentPosition.copyFrom(this.position);
  16997. }
  16998. currentPosition.subtractInPlace(camera.globalPosition);
  16999. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17000. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17001. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17002. }
  17003. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17004. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17005. }
  17006. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17007. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17008. }
  17009. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17010. }
  17011. else {
  17012. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17013. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17014. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17015. }
  17016. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17017. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17018. }
  17019. // Local world
  17020. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17021. // Parent
  17022. if (this.parent && this.parent.getWorldMatrix) {
  17023. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17024. if (this._transformToBoneReferal) {
  17025. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17026. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17027. }
  17028. else {
  17029. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17030. }
  17031. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17032. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17033. this._worldMatrix.copyFrom(this._localWorld);
  17034. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17035. }
  17036. else {
  17037. if (this._transformToBoneReferal) {
  17038. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17039. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17040. }
  17041. else {
  17042. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17043. }
  17044. }
  17045. this._markSyncedWithParent();
  17046. }
  17047. else {
  17048. this._worldMatrix.copyFrom(this._localWorld);
  17049. }
  17050. // Post multiply inverse of pivotMatrix
  17051. if (this._postMultiplyPivotMatrix) {
  17052. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17053. }
  17054. // Normal matrix
  17055. if (this.scaling.isNonUniform) {
  17056. this._updateNonUniformScalingState(true);
  17057. }
  17058. else if (this.parent && this.parent._nonUniformScaling) {
  17059. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17060. }
  17061. else {
  17062. this._updateNonUniformScalingState(false);
  17063. }
  17064. this._afterComputeWorldMatrix();
  17065. // Absolute position
  17066. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17067. // Callbacks
  17068. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17069. if (!this._poseMatrix) {
  17070. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17071. }
  17072. // Cache the determinant
  17073. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17074. return this._worldMatrix;
  17075. };
  17076. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17077. };
  17078. /**
  17079. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17080. * @param func: callback function to add
  17081. *
  17082. * Returns the TransformNode.
  17083. */
  17084. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17085. this.onAfterWorldMatrixUpdateObservable.add(func);
  17086. return this;
  17087. };
  17088. /**
  17089. * Removes a registered callback function.
  17090. * Returns the TransformNode.
  17091. */
  17092. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17093. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17094. return this;
  17095. };
  17096. /**
  17097. * Clone the current transform node
  17098. * Returns the new transform node
  17099. * @param name Name of the new clone
  17100. * @param newParent New parent for the clone
  17101. * @param doNotCloneChildren Do not clone children hierarchy
  17102. */
  17103. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17104. var _this = this;
  17105. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17106. result.name = name;
  17107. result.id = name;
  17108. if (newParent) {
  17109. result.parent = newParent;
  17110. }
  17111. if (!doNotCloneChildren) {
  17112. // Children
  17113. var directDescendants = this.getDescendants(true);
  17114. for (var index = 0; index < directDescendants.length; index++) {
  17115. var child = directDescendants[index];
  17116. if (child.clone) {
  17117. child.clone(name + "." + child.name, result);
  17118. }
  17119. }
  17120. }
  17121. return result;
  17122. };
  17123. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17124. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17125. serializationObject.type = this.getClassName();
  17126. // Parent
  17127. if (this.parent) {
  17128. serializationObject.parentId = this.parent.id;
  17129. }
  17130. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17131. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17132. }
  17133. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17134. serializationObject.isEnabled = this.isEnabled();
  17135. // Parent
  17136. if (this.parent) {
  17137. serializationObject.parentId = this.parent.id;
  17138. }
  17139. return serializationObject;
  17140. };
  17141. // Statics
  17142. /**
  17143. * Returns a new TransformNode object parsed from the source provided.
  17144. * The parameter `parsedMesh` is the source.
  17145. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17146. */
  17147. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17148. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17149. if (BABYLON.Tags) {
  17150. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17151. }
  17152. if (parsedTransformNode.localMatrix) {
  17153. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17154. }
  17155. else if (parsedTransformNode.pivotMatrix) {
  17156. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17157. }
  17158. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17159. // Parent
  17160. if (parsedTransformNode.parentId) {
  17161. transformNode._waitingParentId = parsedTransformNode.parentId;
  17162. }
  17163. return transformNode;
  17164. };
  17165. /**
  17166. * Releases resources associated with this transform node.
  17167. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17168. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17169. */
  17170. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17171. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17172. // Animations
  17173. this.getScene().stopAnimation(this);
  17174. // Remove from scene
  17175. this.getScene().removeTransformNode(this);
  17176. this.onAfterWorldMatrixUpdateObservable.clear();
  17177. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17178. };
  17179. // Statics
  17180. TransformNode.BILLBOARDMODE_NONE = 0;
  17181. TransformNode.BILLBOARDMODE_X = 1;
  17182. TransformNode.BILLBOARDMODE_Y = 2;
  17183. TransformNode.BILLBOARDMODE_Z = 4;
  17184. TransformNode.BILLBOARDMODE_ALL = 7;
  17185. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17186. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17187. __decorate([
  17188. BABYLON.serializeAsVector3()
  17189. ], TransformNode.prototype, "_rotation", void 0);
  17190. __decorate([
  17191. BABYLON.serializeAsQuaternion()
  17192. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17193. __decorate([
  17194. BABYLON.serializeAsVector3()
  17195. ], TransformNode.prototype, "_scaling", void 0);
  17196. __decorate([
  17197. BABYLON.serialize()
  17198. ], TransformNode.prototype, "billboardMode", void 0);
  17199. __decorate([
  17200. BABYLON.serialize()
  17201. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17202. __decorate([
  17203. BABYLON.serialize()
  17204. ], TransformNode.prototype, "infiniteDistance", void 0);
  17205. __decorate([
  17206. BABYLON.serializeAsVector3()
  17207. ], TransformNode.prototype, "position", void 0);
  17208. return TransformNode;
  17209. }(BABYLON.Node));
  17210. BABYLON.TransformNode = TransformNode;
  17211. })(BABYLON || (BABYLON = {}));
  17212. //# sourceMappingURL=babylon.transformNode.js.map
  17213. var BABYLON;
  17214. (function (BABYLON) {
  17215. var AbstractMesh = /** @class */ (function (_super) {
  17216. __extends(AbstractMesh, _super);
  17217. // Constructor
  17218. function AbstractMesh(name, scene) {
  17219. if (scene === void 0) { scene = null; }
  17220. var _this = _super.call(this, name, scene, false) || this;
  17221. _this._facetNb = 0; // facet number
  17222. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17223. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17224. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17225. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17226. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17227. _this._subDiv = {
  17228. max: 1,
  17229. X: 1,
  17230. Y: 1,
  17231. Z: 1
  17232. };
  17233. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17234. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17235. // Events
  17236. /**
  17237. * An event triggered when this mesh collides with another one
  17238. * @type {BABYLON.Observable}
  17239. */
  17240. _this.onCollideObservable = new BABYLON.Observable();
  17241. /**
  17242. * An event triggered when the collision's position changes
  17243. * @type {BABYLON.Observable}
  17244. */
  17245. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17246. /**
  17247. * An event triggered when material is changed
  17248. * @type {BABYLON.Observable}
  17249. */
  17250. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17251. // Properties
  17252. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17253. /**
  17254. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17255. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17256. * or
  17257. * 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.
  17258. * for more info check WebGl documentations
  17259. */
  17260. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17261. /**
  17262. * 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:
  17263. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17264. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17265. * 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.
  17266. */
  17267. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17268. /**
  17269. * 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.
  17270. * The default value is -1 which means don't break the query and wait till the result.
  17271. */
  17272. _this.occlusionRetryCount = -1;
  17273. _this._occlusionInternalRetryCounter = 0;
  17274. _this._isOccluded = false;
  17275. _this._isOcclusionQueryInProgress = false;
  17276. _this._visibility = 1.0;
  17277. _this.alphaIndex = Number.MAX_VALUE;
  17278. _this.isVisible = true;
  17279. _this.isPickable = true;
  17280. _this.showBoundingBox = false;
  17281. _this.showSubMeshesBoundingBox = false;
  17282. _this.isBlocker = false;
  17283. _this.enablePointerMoveEvents = false;
  17284. _this.renderingGroupId = 0;
  17285. _this._receiveShadows = false;
  17286. _this.renderOutline = false;
  17287. _this.outlineColor = BABYLON.Color3.Red();
  17288. _this.outlineWidth = 0.02;
  17289. _this.renderOverlay = false;
  17290. _this.overlayColor = BABYLON.Color3.Red();
  17291. _this.overlayAlpha = 0.5;
  17292. _this._hasVertexAlpha = false;
  17293. _this._useVertexColors = true;
  17294. _this._computeBonesUsingShaders = true;
  17295. _this._numBoneInfluencers = 4;
  17296. _this._applyFog = true;
  17297. _this.useOctreeForRenderingSelection = true;
  17298. _this.useOctreeForPicking = true;
  17299. _this.useOctreeForCollisions = true;
  17300. _this._layerMask = 0x0FFFFFFF;
  17301. /**
  17302. * True if the mesh must be rendered in any case.
  17303. */
  17304. _this.alwaysSelectAsActiveMesh = false;
  17305. /**
  17306. * This scene's action manager
  17307. * @type {BABYLON.ActionManager}
  17308. */
  17309. _this.actionManager = null;
  17310. // Physics
  17311. _this.physicsImpostor = null;
  17312. // Collisions
  17313. _this._checkCollisions = false;
  17314. _this._collisionMask = -1;
  17315. _this._collisionGroup = -1;
  17316. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17317. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17318. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17319. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17320. // Edges
  17321. _this.edgesWidth = 1;
  17322. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17323. // Cache
  17324. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17325. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17326. _this._renderId = 0;
  17327. _this._intersectionsInProgress = new Array();
  17328. _this._unIndexed = false;
  17329. _this._lightSources = new Array();
  17330. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17331. if (collidedMesh === void 0) { collidedMesh = null; }
  17332. //TODO move this to the collision coordinator!
  17333. if (_this.getScene().workerCollisions)
  17334. newPosition.multiplyInPlace(_this._collider._radius);
  17335. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17336. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17337. _this.position.addInPlace(_this._diffPositionForCollisions);
  17338. }
  17339. if (collidedMesh) {
  17340. _this.onCollideObservable.notifyObservers(collidedMesh);
  17341. }
  17342. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17343. };
  17344. _this.getScene().addMesh(_this);
  17345. _this._resyncLightSources();
  17346. return _this;
  17347. }
  17348. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17349. get: function () {
  17350. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17351. },
  17352. enumerable: true,
  17353. configurable: true
  17354. });
  17355. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17356. get: function () {
  17357. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17358. },
  17359. enumerable: true,
  17360. configurable: true
  17361. });
  17362. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17363. get: function () {
  17364. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17365. },
  17366. enumerable: true,
  17367. configurable: true
  17368. });
  17369. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17370. get: function () {
  17371. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17372. },
  17373. enumerable: true,
  17374. configurable: true
  17375. });
  17376. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17377. get: function () {
  17378. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17379. },
  17380. enumerable: true,
  17381. configurable: true
  17382. });
  17383. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17384. /**
  17385. * Read-only : the number of facets in the mesh
  17386. */
  17387. get: function () {
  17388. return this._facetNb;
  17389. },
  17390. enumerable: true,
  17391. configurable: true
  17392. });
  17393. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17394. /**
  17395. * The number (integer) of subdivisions per axis in the partioning space
  17396. */
  17397. get: function () {
  17398. return this._partitioningSubdivisions;
  17399. },
  17400. set: function (nb) {
  17401. this._partitioningSubdivisions = nb;
  17402. },
  17403. enumerable: true,
  17404. configurable: true
  17405. });
  17406. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17407. /**
  17408. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17409. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17410. */
  17411. get: function () {
  17412. return this._partitioningBBoxRatio;
  17413. },
  17414. set: function (ratio) {
  17415. this._partitioningBBoxRatio = ratio;
  17416. },
  17417. enumerable: true,
  17418. configurable: true
  17419. });
  17420. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17421. /**
  17422. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17423. * Works only for updatable meshes.
  17424. * Doesn't work with multi-materials.
  17425. */
  17426. get: function () {
  17427. return this._facetDepthSort;
  17428. },
  17429. set: function (sort) {
  17430. this._facetDepthSort = sort;
  17431. },
  17432. enumerable: true,
  17433. configurable: true
  17434. });
  17435. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17436. /**
  17437. * The location (Vector3) where the facet depth sort must be computed from.
  17438. * By default, the active camera position.
  17439. * Used only when facet depth sort is enabled.
  17440. */
  17441. get: function () {
  17442. return this._facetDepthSortFrom;
  17443. },
  17444. set: function (location) {
  17445. this._facetDepthSortFrom = location;
  17446. },
  17447. enumerable: true,
  17448. configurable: true
  17449. });
  17450. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17451. /**
  17452. * Read-only boolean : is the feature facetData enabled ?
  17453. */
  17454. get: function () {
  17455. return this._facetDataEnabled;
  17456. },
  17457. enumerable: true,
  17458. configurable: true
  17459. });
  17460. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17461. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17462. return false;
  17463. }
  17464. this._markSubMeshesAsMiscDirty();
  17465. return true;
  17466. };
  17467. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17468. set: function (callback) {
  17469. if (this._onCollideObserver) {
  17470. this.onCollideObservable.remove(this._onCollideObserver);
  17471. }
  17472. this._onCollideObserver = this.onCollideObservable.add(callback);
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17478. set: function (callback) {
  17479. if (this._onCollisionPositionChangeObserver) {
  17480. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17481. }
  17482. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17483. },
  17484. enumerable: true,
  17485. configurable: true
  17486. });
  17487. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17488. /**
  17489. * 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.
  17490. */
  17491. get: function () {
  17492. return this._isOccluded;
  17493. },
  17494. set: function (value) {
  17495. this._isOccluded = value;
  17496. },
  17497. enumerable: true,
  17498. configurable: true
  17499. });
  17500. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17501. /**
  17502. * Flag to check the progress status of the query
  17503. */
  17504. get: function () {
  17505. return this._isOcclusionQueryInProgress;
  17506. },
  17507. enumerable: true,
  17508. configurable: true
  17509. });
  17510. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17511. /**
  17512. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17513. */
  17514. get: function () {
  17515. return this._visibility;
  17516. },
  17517. /**
  17518. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17519. */
  17520. set: function (value) {
  17521. if (this._visibility === value) {
  17522. return;
  17523. }
  17524. this._visibility = value;
  17525. this._markSubMeshesAsMiscDirty();
  17526. },
  17527. enumerable: true,
  17528. configurable: true
  17529. });
  17530. Object.defineProperty(AbstractMesh.prototype, "material", {
  17531. get: function () {
  17532. return this._material;
  17533. },
  17534. set: function (value) {
  17535. if (this._material === value) {
  17536. return;
  17537. }
  17538. this._material = value;
  17539. if (this.onMaterialChangedObservable.hasObservers) {
  17540. this.onMaterialChangedObservable.notifyObservers(this);
  17541. }
  17542. if (!this.subMeshes) {
  17543. return;
  17544. }
  17545. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17546. var subMesh = _a[_i];
  17547. subMesh.setEffect(null);
  17548. }
  17549. },
  17550. enumerable: true,
  17551. configurable: true
  17552. });
  17553. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17554. get: function () {
  17555. return this._receiveShadows;
  17556. },
  17557. set: function (value) {
  17558. if (this._receiveShadows === value) {
  17559. return;
  17560. }
  17561. this._receiveShadows = value;
  17562. this._markSubMeshesAsLightDirty();
  17563. },
  17564. enumerable: true,
  17565. configurable: true
  17566. });
  17567. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17568. get: function () {
  17569. return this._hasVertexAlpha;
  17570. },
  17571. set: function (value) {
  17572. if (this._hasVertexAlpha === value) {
  17573. return;
  17574. }
  17575. this._hasVertexAlpha = value;
  17576. this._markSubMeshesAsAttributesDirty();
  17577. this._markSubMeshesAsMiscDirty();
  17578. },
  17579. enumerable: true,
  17580. configurable: true
  17581. });
  17582. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17583. get: function () {
  17584. return this._useVertexColors;
  17585. },
  17586. set: function (value) {
  17587. if (this._useVertexColors === value) {
  17588. return;
  17589. }
  17590. this._useVertexColors = value;
  17591. this._markSubMeshesAsAttributesDirty();
  17592. },
  17593. enumerable: true,
  17594. configurable: true
  17595. });
  17596. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17597. get: function () {
  17598. return this._computeBonesUsingShaders;
  17599. },
  17600. set: function (value) {
  17601. if (this._computeBonesUsingShaders === value) {
  17602. return;
  17603. }
  17604. this._computeBonesUsingShaders = value;
  17605. this._markSubMeshesAsAttributesDirty();
  17606. },
  17607. enumerable: true,
  17608. configurable: true
  17609. });
  17610. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17611. get: function () {
  17612. return this._numBoneInfluencers;
  17613. },
  17614. set: function (value) {
  17615. if (this._numBoneInfluencers === value) {
  17616. return;
  17617. }
  17618. this._numBoneInfluencers = value;
  17619. this._markSubMeshesAsAttributesDirty();
  17620. },
  17621. enumerable: true,
  17622. configurable: true
  17623. });
  17624. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17625. get: function () {
  17626. return this._applyFog;
  17627. },
  17628. set: function (value) {
  17629. if (this._applyFog === value) {
  17630. return;
  17631. }
  17632. this._applyFog = value;
  17633. this._markSubMeshesAsMiscDirty();
  17634. },
  17635. enumerable: true,
  17636. configurable: true
  17637. });
  17638. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17639. get: function () {
  17640. return this._layerMask;
  17641. },
  17642. set: function (value) {
  17643. if (value === this._layerMask) {
  17644. return;
  17645. }
  17646. this._layerMask = value;
  17647. this._resyncLightSources();
  17648. },
  17649. enumerable: true,
  17650. configurable: true
  17651. });
  17652. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17653. get: function () {
  17654. return this._collisionMask;
  17655. },
  17656. set: function (mask) {
  17657. this._collisionMask = !isNaN(mask) ? mask : -1;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17663. get: function () {
  17664. return this._collisionGroup;
  17665. },
  17666. set: function (mask) {
  17667. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17668. },
  17669. enumerable: true,
  17670. configurable: true
  17671. });
  17672. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17673. get: function () {
  17674. return null;
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17680. get: function () {
  17681. return this._skeleton;
  17682. },
  17683. set: function (value) {
  17684. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17685. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17686. }
  17687. if (value && value.needInitialSkinMatrix) {
  17688. value._registerMeshWithPoseMatrix(this);
  17689. }
  17690. this._skeleton = value;
  17691. if (!this._skeleton) {
  17692. this._bonesTransformMatrices = null;
  17693. }
  17694. this._markSubMeshesAsAttributesDirty();
  17695. },
  17696. enumerable: true,
  17697. configurable: true
  17698. });
  17699. /**
  17700. * Returns the string "AbstractMesh"
  17701. */
  17702. AbstractMesh.prototype.getClassName = function () {
  17703. return "AbstractMesh";
  17704. };
  17705. /**
  17706. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17707. */
  17708. AbstractMesh.prototype.toString = function (fullDetails) {
  17709. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17710. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17711. if (this._skeleton) {
  17712. ret += ", skeleton: " + this._skeleton.name;
  17713. }
  17714. if (fullDetails) {
  17715. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17716. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17717. }
  17718. return ret;
  17719. };
  17720. AbstractMesh.prototype._rebuild = function () {
  17721. if (this._occlusionQuery) {
  17722. this._occlusionQuery = null;
  17723. }
  17724. if (this._edgesRenderer) {
  17725. this._edgesRenderer._rebuild();
  17726. }
  17727. if (!this.subMeshes) {
  17728. return;
  17729. }
  17730. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17731. var subMesh = _a[_i];
  17732. subMesh._rebuild();
  17733. }
  17734. };
  17735. AbstractMesh.prototype._resyncLightSources = function () {
  17736. this._lightSources.length = 0;
  17737. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17738. var light = _a[_i];
  17739. if (!light.isEnabled()) {
  17740. continue;
  17741. }
  17742. if (light.canAffectMesh(this)) {
  17743. this._lightSources.push(light);
  17744. }
  17745. }
  17746. this._markSubMeshesAsLightDirty();
  17747. };
  17748. AbstractMesh.prototype._resyncLighSource = function (light) {
  17749. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17750. var index = this._lightSources.indexOf(light);
  17751. if (index === -1) {
  17752. if (!isIn) {
  17753. return;
  17754. }
  17755. this._lightSources.push(light);
  17756. }
  17757. else {
  17758. if (isIn) {
  17759. return;
  17760. }
  17761. this._lightSources.splice(index, 1);
  17762. }
  17763. this._markSubMeshesAsLightDirty();
  17764. };
  17765. AbstractMesh.prototype._removeLightSource = function (light) {
  17766. var index = this._lightSources.indexOf(light);
  17767. if (index === -1) {
  17768. return;
  17769. }
  17770. this._lightSources.splice(index, 1);
  17771. this._markSubMeshesAsLightDirty();
  17772. };
  17773. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17774. if (!this.subMeshes) {
  17775. return;
  17776. }
  17777. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17778. var subMesh = _a[_i];
  17779. if (subMesh._materialDefines) {
  17780. func(subMesh._materialDefines);
  17781. }
  17782. }
  17783. };
  17784. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17785. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17786. };
  17787. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17788. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17789. };
  17790. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17791. if (!this.subMeshes) {
  17792. return;
  17793. }
  17794. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17795. var subMesh = _a[_i];
  17796. var material = subMesh.getMaterial();
  17797. if (material) {
  17798. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17799. }
  17800. }
  17801. };
  17802. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17803. /**
  17804. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17805. * Default : (1.0, 1.0, 1.0)
  17806. */
  17807. get: function () {
  17808. return this._scaling;
  17809. },
  17810. /**
  17811. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17812. * Default : (1.0, 1.0, 1.0)
  17813. */
  17814. set: function (newScaling) {
  17815. this._scaling = newScaling;
  17816. if (this.physicsImpostor) {
  17817. this.physicsImpostor.forceUpdate();
  17818. }
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. // Methods
  17824. /**
  17825. * Disables the mesh edger rendering mode.
  17826. * Returns the AbstractMesh.
  17827. */
  17828. AbstractMesh.prototype.disableEdgesRendering = function () {
  17829. if (this._edgesRenderer) {
  17830. this._edgesRenderer.dispose();
  17831. this._edgesRenderer = null;
  17832. }
  17833. return this;
  17834. };
  17835. /**
  17836. * Enables the edge rendering mode on the mesh.
  17837. * This mode makes the mesh edges visible.
  17838. * Returns the AbstractMesh.
  17839. */
  17840. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17841. if (epsilon === void 0) { epsilon = 0.95; }
  17842. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17843. this.disableEdgesRendering();
  17844. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17845. return this;
  17846. };
  17847. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17848. /**
  17849. * Returns true if the mesh is blocked. Used by the class Mesh.
  17850. * Returns the boolean `false` by default.
  17851. */
  17852. get: function () {
  17853. return false;
  17854. },
  17855. enumerable: true,
  17856. configurable: true
  17857. });
  17858. /**
  17859. * Returns the mesh itself by default, used by the class Mesh.
  17860. * Returned type : AbstractMesh
  17861. */
  17862. AbstractMesh.prototype.getLOD = function (camera) {
  17863. return this;
  17864. };
  17865. /**
  17866. * Returns 0 by default, used by the class Mesh.
  17867. * Returns an integer.
  17868. */
  17869. AbstractMesh.prototype.getTotalVertices = function () {
  17870. return 0;
  17871. };
  17872. /**
  17873. * Returns null by default, used by the class Mesh.
  17874. * Returned type : integer array
  17875. */
  17876. AbstractMesh.prototype.getIndices = function () {
  17877. return null;
  17878. };
  17879. /**
  17880. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17881. * Returned type : float array or Float32Array
  17882. */
  17883. AbstractMesh.prototype.getVerticesData = function (kind) {
  17884. return null;
  17885. };
  17886. /**
  17887. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17888. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17889. * The `data` are either a numeric array either a Float32Array.
  17890. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17891. * 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).
  17892. * Note that a new underlying VertexBuffer object is created each call.
  17893. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17894. *
  17895. * Possible `kind` values :
  17896. * - BABYLON.VertexBuffer.PositionKind
  17897. * - BABYLON.VertexBuffer.UVKind
  17898. * - BABYLON.VertexBuffer.UV2Kind
  17899. * - BABYLON.VertexBuffer.UV3Kind
  17900. * - BABYLON.VertexBuffer.UV4Kind
  17901. * - BABYLON.VertexBuffer.UV5Kind
  17902. * - BABYLON.VertexBuffer.UV6Kind
  17903. * - BABYLON.VertexBuffer.ColorKind
  17904. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17905. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17906. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17907. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17908. *
  17909. * Returns the Mesh.
  17910. */
  17911. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17912. return this;
  17913. };
  17914. /**
  17915. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17916. * If the mesh has no geometry, it is simply returned as it is.
  17917. * The `data` are either a numeric array either a Float32Array.
  17918. * No new underlying VertexBuffer object is created.
  17919. * 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.
  17920. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17921. *
  17922. * Possible `kind` values :
  17923. * - BABYLON.VertexBuffer.PositionKind
  17924. * - BABYLON.VertexBuffer.UVKind
  17925. * - BABYLON.VertexBuffer.UV2Kind
  17926. * - BABYLON.VertexBuffer.UV3Kind
  17927. * - BABYLON.VertexBuffer.UV4Kind
  17928. * - BABYLON.VertexBuffer.UV5Kind
  17929. * - BABYLON.VertexBuffer.UV6Kind
  17930. * - BABYLON.VertexBuffer.ColorKind
  17931. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17932. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17933. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17934. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17935. *
  17936. * Returns the Mesh.
  17937. */
  17938. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17939. return this;
  17940. };
  17941. /**
  17942. * Sets the mesh indices.
  17943. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17944. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17945. * This method creates a new index buffer each call.
  17946. * Returns the Mesh.
  17947. */
  17948. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17949. return this;
  17950. };
  17951. /** Returns false by default, used by the class Mesh.
  17952. * Returns a boolean
  17953. */
  17954. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17955. return false;
  17956. };
  17957. /**
  17958. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17959. * Returns a BoundingInfo
  17960. */
  17961. AbstractMesh.prototype.getBoundingInfo = function () {
  17962. if (this._masterMesh) {
  17963. return this._masterMesh.getBoundingInfo();
  17964. }
  17965. if (!this._boundingInfo) {
  17966. // this._boundingInfo is being created here
  17967. this._updateBoundingInfo();
  17968. }
  17969. // cannot be null.
  17970. return this._boundingInfo;
  17971. };
  17972. /**
  17973. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17974. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17975. */
  17976. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17977. if (includeDescendants === void 0) { includeDescendants = true; }
  17978. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17979. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17980. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17981. if (maxDimension === 0) {
  17982. return this;
  17983. }
  17984. var scale = 1 / maxDimension;
  17985. this.scaling.scaleInPlace(scale);
  17986. return this;
  17987. };
  17988. /**
  17989. * Sets a mesh new object BoundingInfo.
  17990. * Returns the AbstractMesh.
  17991. */
  17992. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17993. this._boundingInfo = boundingInfo;
  17994. return this;
  17995. };
  17996. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17997. get: function () {
  17998. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. AbstractMesh.prototype._preActivate = function () {
  18004. };
  18005. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18006. };
  18007. AbstractMesh.prototype._activate = function (renderId) {
  18008. this._renderId = renderId;
  18009. };
  18010. /**
  18011. * Returns the latest update of the World matrix
  18012. * Returns a Matrix.
  18013. */
  18014. AbstractMesh.prototype.getWorldMatrix = function () {
  18015. if (this._masterMesh) {
  18016. return this._masterMesh.getWorldMatrix();
  18017. }
  18018. return _super.prototype.getWorldMatrix.call(this);
  18019. };
  18020. /**
  18021. * Returns the latest update of the World matrix determinant.
  18022. */
  18023. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18024. if (this._masterMesh) {
  18025. return this._masterMesh._getWorldMatrixDeterminant();
  18026. }
  18027. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18028. };
  18029. // ================================== Point of View Movement =================================
  18030. /**
  18031. * Perform relative position change from the point of view of behind the front of the mesh.
  18032. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18033. * Supports definition of mesh facing forward or backward.
  18034. * @param {number} amountRight
  18035. * @param {number} amountUp
  18036. * @param {number} amountForward
  18037. *
  18038. * Returns the AbstractMesh.
  18039. */
  18040. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18041. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18042. return this;
  18043. };
  18044. /**
  18045. * Calculate relative position change from the point of view of behind the front of the mesh.
  18046. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18047. * Supports definition of mesh facing forward or backward.
  18048. * @param {number} amountRight
  18049. * @param {number} amountUp
  18050. * @param {number} amountForward
  18051. *
  18052. * Returns a new Vector3.
  18053. */
  18054. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18055. var rotMatrix = new BABYLON.Matrix();
  18056. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18057. rotQuaternion.toRotationMatrix(rotMatrix);
  18058. var translationDelta = BABYLON.Vector3.Zero();
  18059. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18060. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18061. return translationDelta;
  18062. };
  18063. // ================================== Point of View Rotation =================================
  18064. /**
  18065. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18066. * Supports definition of mesh facing forward or backward.
  18067. * @param {number} flipBack
  18068. * @param {number} twirlClockwise
  18069. * @param {number} tiltRight
  18070. *
  18071. * Returns the AbstractMesh.
  18072. */
  18073. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18074. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18075. return this;
  18076. };
  18077. /**
  18078. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18079. * Supports definition of mesh facing forward or backward.
  18080. * @param {number} flipBack
  18081. * @param {number} twirlClockwise
  18082. * @param {number} tiltRight
  18083. *
  18084. * Returns a new Vector3.
  18085. */
  18086. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18087. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18088. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18089. };
  18090. /**
  18091. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18092. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18093. */
  18094. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18095. if (includeDescendants === void 0) { includeDescendants = true; }
  18096. this.computeWorldMatrix(true);
  18097. var min;
  18098. var max;
  18099. var boundingInfo = this.getBoundingInfo();
  18100. if (!this.subMeshes) {
  18101. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18102. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18103. }
  18104. else {
  18105. min = boundingInfo.boundingBox.minimumWorld;
  18106. max = boundingInfo.boundingBox.maximumWorld;
  18107. }
  18108. if (includeDescendants) {
  18109. var descendants = this.getDescendants(false);
  18110. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18111. var descendant = descendants_1[_i];
  18112. var childMesh = descendant;
  18113. childMesh.computeWorldMatrix(true);
  18114. //make sure we have the needed params to get mix and max
  18115. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18116. continue;
  18117. }
  18118. var childBoundingInfo = childMesh.getBoundingInfo();
  18119. var boundingBox = childBoundingInfo.boundingBox;
  18120. var minBox = boundingBox.minimumWorld;
  18121. var maxBox = boundingBox.maximumWorld;
  18122. BABYLON.Tools.CheckExtends(minBox, min, max);
  18123. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18124. }
  18125. }
  18126. return {
  18127. min: min,
  18128. max: max
  18129. };
  18130. };
  18131. /**
  18132. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18133. * Returns the AbstractMesh.
  18134. */
  18135. AbstractMesh.prototype._updateBoundingInfo = function () {
  18136. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18137. this._boundingInfo.update(this.worldMatrixFromCache);
  18138. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18139. return this;
  18140. };
  18141. /**
  18142. * Update a mesh's children BoundingInfo objects only.
  18143. * Returns the AbstractMesh.
  18144. */
  18145. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18146. if (!this.subMeshes) {
  18147. return this;
  18148. }
  18149. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18150. var subMesh = this.subMeshes[subIndex];
  18151. if (!subMesh.IsGlobal) {
  18152. subMesh.updateBoundingInfo(matrix);
  18153. }
  18154. }
  18155. return this;
  18156. };
  18157. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18158. // Bounding info
  18159. this._updateBoundingInfo();
  18160. };
  18161. /**
  18162. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18163. * A mesh is in the frustum if its bounding box intersects the frustum.
  18164. * Boolean returned.
  18165. */
  18166. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18167. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18168. };
  18169. /**
  18170. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18171. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18172. * Boolean returned.
  18173. */
  18174. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18175. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18176. ;
  18177. };
  18178. /**
  18179. * True if the mesh intersects another mesh or a SolidParticle object.
  18180. * 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)
  18181. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18182. * Returns a boolean.
  18183. */
  18184. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18185. if (precise === void 0) { precise = false; }
  18186. if (!this._boundingInfo || !mesh._boundingInfo) {
  18187. return false;
  18188. }
  18189. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18190. return true;
  18191. }
  18192. if (includeDescendants) {
  18193. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18194. var child = _a[_i];
  18195. if (child.intersectsMesh(mesh, precise, true)) {
  18196. return true;
  18197. }
  18198. }
  18199. }
  18200. return false;
  18201. };
  18202. /**
  18203. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18204. * Returns a boolean.
  18205. */
  18206. AbstractMesh.prototype.intersectsPoint = function (point) {
  18207. if (!this._boundingInfo) {
  18208. return false;
  18209. }
  18210. return this._boundingInfo.intersectsPoint(point);
  18211. };
  18212. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18213. return this.physicsImpostor;
  18214. };
  18215. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18216. if (camera === void 0) { camera = null; }
  18217. if (!camera) {
  18218. camera = this.getScene().activeCamera;
  18219. }
  18220. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18221. };
  18222. /**
  18223. * Returns the distance from the mesh to the active camera.
  18224. * Returns a float.
  18225. */
  18226. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18227. if (camera === void 0) { camera = null; }
  18228. if (!camera) {
  18229. camera = this.getScene().activeCamera;
  18230. }
  18231. return this.absolutePosition.subtract(camera.position).length();
  18232. };
  18233. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18234. if (!this.physicsImpostor) {
  18235. return this;
  18236. }
  18237. this.physicsImpostor.applyImpulse(force, contactPoint);
  18238. return this;
  18239. };
  18240. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18241. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18242. return this;
  18243. }
  18244. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18245. mainPivot: pivot1,
  18246. connectedPivot: pivot2,
  18247. nativeParams: options
  18248. });
  18249. return this;
  18250. };
  18251. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18252. // Collisions
  18253. /**
  18254. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18255. * Default `false`.
  18256. */
  18257. get: function () {
  18258. return this._checkCollisions;
  18259. },
  18260. set: function (collisionEnabled) {
  18261. this._checkCollisions = collisionEnabled;
  18262. if (this.getScene().workerCollisions) {
  18263. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18264. }
  18265. },
  18266. enumerable: true,
  18267. configurable: true
  18268. });
  18269. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18270. /**
  18271. * Gets Collider object used to compute collisions (not physics)
  18272. */
  18273. get: function () {
  18274. return this._collider;
  18275. },
  18276. enumerable: true,
  18277. configurable: true
  18278. });
  18279. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18280. var globalPosition = this.getAbsolutePosition();
  18281. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18282. if (!this._collider) {
  18283. this._collider = new BABYLON.Collider();
  18284. }
  18285. this._collider._radius = this.ellipsoid;
  18286. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18287. return this;
  18288. };
  18289. // Submeshes octree
  18290. /**
  18291. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18292. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18293. * Returns an Octree of submeshes.
  18294. */
  18295. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18296. if (maxCapacity === void 0) { maxCapacity = 64; }
  18297. if (maxDepth === void 0) { maxDepth = 2; }
  18298. if (!this._submeshesOctree) {
  18299. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18300. }
  18301. this.computeWorldMatrix(true);
  18302. var boundingInfo = this.getBoundingInfo();
  18303. // Update octree
  18304. var bbox = boundingInfo.boundingBox;
  18305. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18306. return this._submeshesOctree;
  18307. };
  18308. // Collisions
  18309. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18310. this._generatePointsArray();
  18311. if (!this._positions) {
  18312. return this;
  18313. }
  18314. // Transformation
  18315. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18316. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18317. subMesh._lastColliderWorldVertices = [];
  18318. subMesh._trianglePlanes = [];
  18319. var start = subMesh.verticesStart;
  18320. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18321. for (var i = start; i < end; i++) {
  18322. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18323. }
  18324. }
  18325. // Collide
  18326. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18327. if (collider.collisionFound) {
  18328. collider.collidedMesh = this;
  18329. }
  18330. return this;
  18331. };
  18332. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18333. var subMeshes;
  18334. var len;
  18335. // Octrees
  18336. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18337. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18338. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18339. len = intersections.length;
  18340. subMeshes = intersections.data;
  18341. }
  18342. else {
  18343. subMeshes = this.subMeshes;
  18344. len = subMeshes.length;
  18345. }
  18346. for (var index = 0; index < len; index++) {
  18347. var subMesh = subMeshes[index];
  18348. // Bounding test
  18349. if (len > 1 && !subMesh._checkCollision(collider))
  18350. continue;
  18351. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18352. }
  18353. return this;
  18354. };
  18355. AbstractMesh.prototype._checkCollision = function (collider) {
  18356. // Bounding box test
  18357. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18358. return this;
  18359. // Transformation matrix
  18360. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18361. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18362. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18363. return this;
  18364. };
  18365. // Picking
  18366. AbstractMesh.prototype._generatePointsArray = function () {
  18367. return false;
  18368. };
  18369. /**
  18370. * Checks if the passed Ray intersects with the mesh.
  18371. * Returns an object PickingInfo.
  18372. */
  18373. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18374. var pickingInfo = new BABYLON.PickingInfo();
  18375. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18376. return pickingInfo;
  18377. }
  18378. if (!this._generatePointsArray()) {
  18379. return pickingInfo;
  18380. }
  18381. var intersectInfo = null;
  18382. // Octrees
  18383. var subMeshes;
  18384. var len;
  18385. if (this._submeshesOctree && this.useOctreeForPicking) {
  18386. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18387. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18388. len = intersections.length;
  18389. subMeshes = intersections.data;
  18390. }
  18391. else {
  18392. subMeshes = this.subMeshes;
  18393. len = subMeshes.length;
  18394. }
  18395. for (var index = 0; index < len; index++) {
  18396. var subMesh = subMeshes[index];
  18397. // Bounding test
  18398. if (len > 1 && !subMesh.canIntersects(ray))
  18399. continue;
  18400. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18401. if (currentIntersectInfo) {
  18402. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18403. intersectInfo = currentIntersectInfo;
  18404. intersectInfo.subMeshId = index;
  18405. if (fastCheck) {
  18406. break;
  18407. }
  18408. }
  18409. }
  18410. }
  18411. if (intersectInfo) {
  18412. // Get picked point
  18413. var world = this.getWorldMatrix();
  18414. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18415. var direction = ray.direction.clone();
  18416. direction = direction.scale(intersectInfo.distance);
  18417. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18418. var pickedPoint = worldOrigin.add(worldDirection);
  18419. // Return result
  18420. pickingInfo.hit = true;
  18421. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18422. pickingInfo.pickedPoint = pickedPoint;
  18423. pickingInfo.pickedMesh = this;
  18424. pickingInfo.bu = intersectInfo.bu || 0;
  18425. pickingInfo.bv = intersectInfo.bv || 0;
  18426. pickingInfo.faceId = intersectInfo.faceId;
  18427. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18428. return pickingInfo;
  18429. }
  18430. return pickingInfo;
  18431. };
  18432. /**
  18433. * Clones the mesh, used by the class Mesh.
  18434. * Just returns `null` for an AbstractMesh.
  18435. */
  18436. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18437. return null;
  18438. };
  18439. /**
  18440. * Disposes all the mesh submeshes.
  18441. * Returns the AbstractMesh.
  18442. */
  18443. AbstractMesh.prototype.releaseSubMeshes = function () {
  18444. if (this.subMeshes) {
  18445. while (this.subMeshes.length) {
  18446. this.subMeshes[0].dispose();
  18447. }
  18448. }
  18449. else {
  18450. this.subMeshes = new Array();
  18451. }
  18452. return this;
  18453. };
  18454. /**
  18455. * Releases resources associated with this abstract mesh.
  18456. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18457. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18458. */
  18459. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18460. var _this = this;
  18461. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18462. var index;
  18463. // Smart Array Retainers.
  18464. this.getScene().freeActiveMeshes();
  18465. this.getScene().freeRenderingGroups();
  18466. // Action manager
  18467. if (this.actionManager !== undefined && this.actionManager !== null) {
  18468. this.actionManager.dispose();
  18469. this.actionManager = null;
  18470. }
  18471. // Skeleton
  18472. this.skeleton = null;
  18473. // Physics
  18474. if (this.physicsImpostor) {
  18475. this.physicsImpostor.dispose();
  18476. }
  18477. // Intersections in progress
  18478. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18479. var other = this._intersectionsInProgress[index];
  18480. var pos = other._intersectionsInProgress.indexOf(this);
  18481. other._intersectionsInProgress.splice(pos, 1);
  18482. }
  18483. this._intersectionsInProgress = [];
  18484. // Lights
  18485. var lights = this.getScene().lights;
  18486. lights.forEach(function (light) {
  18487. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18488. if (meshIndex !== -1) {
  18489. light.includedOnlyMeshes.splice(meshIndex, 1);
  18490. }
  18491. meshIndex = light.excludedMeshes.indexOf(_this);
  18492. if (meshIndex !== -1) {
  18493. light.excludedMeshes.splice(meshIndex, 1);
  18494. }
  18495. // Shadow generators
  18496. var generator = light.getShadowGenerator();
  18497. if (generator) {
  18498. var shadowMap = generator.getShadowMap();
  18499. if (shadowMap && shadowMap.renderList) {
  18500. meshIndex = shadowMap.renderList.indexOf(_this);
  18501. if (meshIndex !== -1) {
  18502. shadowMap.renderList.splice(meshIndex, 1);
  18503. }
  18504. }
  18505. }
  18506. });
  18507. // Edges
  18508. if (this._edgesRenderer) {
  18509. this._edgesRenderer.dispose();
  18510. this._edgesRenderer = null;
  18511. }
  18512. // SubMeshes
  18513. if (this.getClassName() !== "InstancedMesh") {
  18514. this.releaseSubMeshes();
  18515. }
  18516. // Octree
  18517. var sceneOctree = this.getScene().selectionOctree;
  18518. if (sceneOctree !== undefined && sceneOctree !== null) {
  18519. var index = sceneOctree.dynamicContent.indexOf(this);
  18520. if (index !== -1) {
  18521. sceneOctree.dynamicContent.splice(index, 1);
  18522. }
  18523. }
  18524. // Query
  18525. var engine = this.getScene().getEngine();
  18526. if (this._occlusionQuery) {
  18527. this._isOcclusionQueryInProgress = false;
  18528. engine.deleteQuery(this._occlusionQuery);
  18529. this._occlusionQuery = null;
  18530. }
  18531. // Engine
  18532. engine.wipeCaches();
  18533. // Remove from scene
  18534. this.getScene().removeMesh(this);
  18535. if (disposeMaterialAndTextures) {
  18536. if (this.material) {
  18537. this.material.dispose(false, true);
  18538. }
  18539. }
  18540. if (!doNotRecurse) {
  18541. // Particles
  18542. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18543. if (this.getScene().particleSystems[index].emitter === this) {
  18544. this.getScene().particleSystems[index].dispose();
  18545. index--;
  18546. }
  18547. }
  18548. }
  18549. // facet data
  18550. if (this._facetDataEnabled) {
  18551. this.disableFacetData();
  18552. }
  18553. this.onAfterWorldMatrixUpdateObservable.clear();
  18554. this.onCollideObservable.clear();
  18555. this.onCollisionPositionChangeObservable.clear();
  18556. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18557. };
  18558. /**
  18559. * Adds the passed mesh as a child to the current mesh.
  18560. * Returns the AbstractMesh.
  18561. */
  18562. AbstractMesh.prototype.addChild = function (mesh) {
  18563. mesh.setParent(this);
  18564. return this;
  18565. };
  18566. /**
  18567. * Removes the passed mesh from the current mesh children list.
  18568. * Returns the AbstractMesh.
  18569. */
  18570. AbstractMesh.prototype.removeChild = function (mesh) {
  18571. mesh.setParent(null);
  18572. return this;
  18573. };
  18574. // Facet data
  18575. /**
  18576. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18577. * Returns the AbstractMesh.
  18578. */
  18579. AbstractMesh.prototype._initFacetData = function () {
  18580. if (!this._facetNormals) {
  18581. this._facetNormals = new Array();
  18582. }
  18583. if (!this._facetPositions) {
  18584. this._facetPositions = new Array();
  18585. }
  18586. if (!this._facetPartitioning) {
  18587. this._facetPartitioning = new Array();
  18588. }
  18589. this._facetNb = (this.getIndices().length / 3) | 0;
  18590. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18591. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18592. for (var f = 0; f < this._facetNb; f++) {
  18593. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18594. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18595. }
  18596. this._facetDataEnabled = true;
  18597. return this;
  18598. };
  18599. /**
  18600. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18601. * This method can be called within the render loop.
  18602. * 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.
  18603. * Returns the AbstractMesh.
  18604. */
  18605. AbstractMesh.prototype.updateFacetData = function () {
  18606. if (!this._facetDataEnabled) {
  18607. this._initFacetData();
  18608. }
  18609. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18610. var indices = this.getIndices();
  18611. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18612. var bInfo = this.getBoundingInfo();
  18613. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18614. // init arrays, matrix and sort function on first call
  18615. this._facetDepthSortEnabled = true;
  18616. if (indices instanceof Uint16Array) {
  18617. this._depthSortedIndices = new Uint16Array(indices);
  18618. }
  18619. else if (indices instanceof Uint32Array) {
  18620. this._depthSortedIndices = new Uint32Array(indices);
  18621. }
  18622. else {
  18623. var needs32bits = false;
  18624. for (var i = 0; i < indices.length; i++) {
  18625. if (indices[i] > 65535) {
  18626. needs32bits = true;
  18627. break;
  18628. }
  18629. }
  18630. if (needs32bits) {
  18631. this._depthSortedIndices = new Uint32Array(indices);
  18632. }
  18633. else {
  18634. this._depthSortedIndices = new Uint16Array(indices);
  18635. }
  18636. }
  18637. this._facetDepthSortFunction = function (f1, f2) {
  18638. return (f2.sqDistance - f1.sqDistance);
  18639. };
  18640. if (!this._facetDepthSortFrom) {
  18641. var camera = this.getScene().activeCamera;
  18642. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18643. }
  18644. this._depthSortedFacets = [];
  18645. for (var f = 0; f < this._facetNb; f++) {
  18646. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18647. this._depthSortedFacets.push(depthSortedFacet);
  18648. }
  18649. this._invertedMatrix = BABYLON.Matrix.Identity();
  18650. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18651. }
  18652. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18653. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18654. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18655. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18656. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18657. this._subDiv.max = this._partitioningSubdivisions;
  18658. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18659. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18660. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18661. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18662. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18663. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18664. // set the parameters for ComputeNormals()
  18665. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18666. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18667. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18668. this._facetParameters.bInfo = bInfo;
  18669. this._facetParameters.bbSize = this._bbSize;
  18670. this._facetParameters.subDiv = this._subDiv;
  18671. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18672. this._facetParameters.depthSort = this._facetDepthSort;
  18673. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18674. this.computeWorldMatrix(true);
  18675. this._worldMatrix.invertToRef(this._invertedMatrix);
  18676. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18677. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18678. }
  18679. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18680. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18681. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18682. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18683. var l = (this._depthSortedIndices.length / 3) | 0;
  18684. for (var f = 0; f < l; f++) {
  18685. var sind = this._depthSortedFacets[f].ind;
  18686. this._depthSortedIndices[f * 3] = indices[sind];
  18687. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18688. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18689. }
  18690. this.updateIndices(this._depthSortedIndices);
  18691. }
  18692. return this;
  18693. };
  18694. /**
  18695. * Returns the facetLocalNormals array.
  18696. * The normals are expressed in the mesh local space.
  18697. */
  18698. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18699. if (!this._facetNormals) {
  18700. this.updateFacetData();
  18701. }
  18702. return this._facetNormals;
  18703. };
  18704. /**
  18705. * Returns the facetLocalPositions array.
  18706. * The facet positions are expressed in the mesh local space.
  18707. */
  18708. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18709. if (!this._facetPositions) {
  18710. this.updateFacetData();
  18711. }
  18712. return this._facetPositions;
  18713. };
  18714. /**
  18715. * Returns the facetLocalPartioning array.
  18716. */
  18717. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18718. if (!this._facetPartitioning) {
  18719. this.updateFacetData();
  18720. }
  18721. return this._facetPartitioning;
  18722. };
  18723. /**
  18724. * Returns the i-th facet position in the world system.
  18725. * This method allocates a new Vector3 per call.
  18726. */
  18727. AbstractMesh.prototype.getFacetPosition = function (i) {
  18728. var pos = BABYLON.Vector3.Zero();
  18729. this.getFacetPositionToRef(i, pos);
  18730. return pos;
  18731. };
  18732. /**
  18733. * Sets the reference Vector3 with the i-th facet position in the world system.
  18734. * Returns the AbstractMesh.
  18735. */
  18736. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18737. var localPos = (this.getFacetLocalPositions())[i];
  18738. var world = this.getWorldMatrix();
  18739. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18740. return this;
  18741. };
  18742. /**
  18743. * Returns the i-th facet normal in the world system.
  18744. * This method allocates a new Vector3 per call.
  18745. */
  18746. AbstractMesh.prototype.getFacetNormal = function (i) {
  18747. var norm = BABYLON.Vector3.Zero();
  18748. this.getFacetNormalToRef(i, norm);
  18749. return norm;
  18750. };
  18751. /**
  18752. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18753. * Returns the AbstractMesh.
  18754. */
  18755. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18756. var localNorm = (this.getFacetLocalNormals())[i];
  18757. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18758. return this;
  18759. };
  18760. /**
  18761. * 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).
  18762. */
  18763. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18764. var bInfo = this.getBoundingInfo();
  18765. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18766. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18767. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18768. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18769. return null;
  18770. }
  18771. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18772. };
  18773. /**
  18774. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18775. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18776. * 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.
  18777. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18778. * 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.
  18779. */
  18780. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18781. if (checkFace === void 0) { checkFace = false; }
  18782. if (facing === void 0) { facing = true; }
  18783. var world = this.getWorldMatrix();
  18784. var invMat = BABYLON.Tmp.Matrix[5];
  18785. world.invertToRef(invMat);
  18786. var invVect = BABYLON.Tmp.Vector3[8];
  18787. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18788. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18789. if (projected) {
  18790. // tranform the local computed projected vector to world coordinates
  18791. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18792. }
  18793. return closest;
  18794. };
  18795. /**
  18796. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18797. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18798. * 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.
  18799. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18800. * 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.
  18801. */
  18802. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18803. if (checkFace === void 0) { checkFace = false; }
  18804. if (facing === void 0) { facing = true; }
  18805. var closest = null;
  18806. var tmpx = 0.0;
  18807. var tmpy = 0.0;
  18808. var tmpz = 0.0;
  18809. var d = 0.0; // tmp dot facet normal * facet position
  18810. var t0 = 0.0;
  18811. var projx = 0.0;
  18812. var projy = 0.0;
  18813. var projz = 0.0;
  18814. // Get all the facets in the same partitioning block than (x, y, z)
  18815. var facetPositions = this.getFacetLocalPositions();
  18816. var facetNormals = this.getFacetLocalNormals();
  18817. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18818. if (!facetsInBlock) {
  18819. return null;
  18820. }
  18821. // Get the closest facet to (x, y, z)
  18822. var shortest = Number.MAX_VALUE; // init distance vars
  18823. var tmpDistance = shortest;
  18824. var fib; // current facet in the block
  18825. var norm; // current facet normal
  18826. var p0; // current facet barycenter position
  18827. // loop on all the facets in the current partitioning block
  18828. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18829. fib = facetsInBlock[idx];
  18830. norm = facetNormals[fib];
  18831. p0 = facetPositions[fib];
  18832. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18833. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18834. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18835. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18836. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18837. projx = x + norm.x * t0;
  18838. projy = y + norm.y * t0;
  18839. projz = z + norm.z * t0;
  18840. tmpx = projx - x;
  18841. tmpy = projy - y;
  18842. tmpz = projz - z;
  18843. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18844. if (tmpDistance < shortest) {
  18845. shortest = tmpDistance;
  18846. closest = fib;
  18847. if (projected) {
  18848. projected.x = projx;
  18849. projected.y = projy;
  18850. projected.z = projz;
  18851. }
  18852. }
  18853. }
  18854. }
  18855. return closest;
  18856. };
  18857. /**
  18858. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18859. */
  18860. AbstractMesh.prototype.getFacetDataParameters = function () {
  18861. return this._facetParameters;
  18862. };
  18863. /**
  18864. * Disables the feature FacetData and frees the related memory.
  18865. * Returns the AbstractMesh.
  18866. */
  18867. AbstractMesh.prototype.disableFacetData = function () {
  18868. if (this._facetDataEnabled) {
  18869. this._facetDataEnabled = false;
  18870. this._facetPositions = new Array();
  18871. this._facetNormals = new Array();
  18872. this._facetPartitioning = new Array();
  18873. this._facetParameters = null;
  18874. this._depthSortedIndices = new Uint32Array(0);
  18875. }
  18876. return this;
  18877. };
  18878. /**
  18879. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18880. * Returns the mesh.
  18881. */
  18882. AbstractMesh.prototype.updateIndices = function (indices) {
  18883. return this;
  18884. };
  18885. /**
  18886. * The mesh Geometry. Actually used by the Mesh object.
  18887. * Returns a blank geometry object.
  18888. */
  18889. /**
  18890. * Creates new normals data for the mesh.
  18891. * @param updatable.
  18892. */
  18893. AbstractMesh.prototype.createNormals = function (updatable) {
  18894. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18895. var indices = this.getIndices();
  18896. var normals;
  18897. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18898. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18899. }
  18900. else {
  18901. normals = [];
  18902. }
  18903. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18904. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18905. };
  18906. /**
  18907. * Align the mesh with a normal.
  18908. * Returns the mesh.
  18909. */
  18910. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18911. if (!upDirection) {
  18912. upDirection = BABYLON.Axis.Y;
  18913. }
  18914. var axisX = BABYLON.Tmp.Vector3[0];
  18915. var axisZ = BABYLON.Tmp.Vector3[1];
  18916. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18917. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18918. if (this.rotationQuaternion) {
  18919. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18920. }
  18921. else {
  18922. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18923. }
  18924. return this;
  18925. };
  18926. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18927. var engine = this.getEngine();
  18928. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18929. this._isOccluded = false;
  18930. return;
  18931. }
  18932. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18933. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18934. if (isOcclusionQueryAvailable) {
  18935. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18936. this._isOcclusionQueryInProgress = false;
  18937. this._occlusionInternalRetryCounter = 0;
  18938. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18939. }
  18940. else {
  18941. this._occlusionInternalRetryCounter++;
  18942. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18943. this._isOcclusionQueryInProgress = false;
  18944. this._occlusionInternalRetryCounter = 0;
  18945. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18946. // if strict continue the last state of the object.
  18947. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18948. }
  18949. else {
  18950. return;
  18951. }
  18952. }
  18953. }
  18954. var scene = this.getScene();
  18955. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18956. if (!this._occlusionQuery) {
  18957. this._occlusionQuery = engine.createQuery();
  18958. }
  18959. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18960. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18961. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18962. this._isOcclusionQueryInProgress = true;
  18963. };
  18964. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18965. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18966. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18967. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18968. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18969. return AbstractMesh;
  18970. }(BABYLON.TransformNode));
  18971. BABYLON.AbstractMesh = AbstractMesh;
  18972. })(BABYLON || (BABYLON = {}));
  18973. //# sourceMappingURL=babylon.abstractMesh.js.map
  18974. var BABYLON;
  18975. (function (BABYLON) {
  18976. /**
  18977. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18978. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18979. * 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.
  18980. */
  18981. var Light = /** @class */ (function (_super) {
  18982. __extends(Light, _super);
  18983. /**
  18984. * Creates a Light object in the scene.
  18985. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18986. * @param name The firendly name of the light
  18987. * @param scene The scene the light belongs too
  18988. */
  18989. function Light(name, scene) {
  18990. var _this = _super.call(this, name, scene) || this;
  18991. /**
  18992. * Diffuse gives the basic color to an object.
  18993. */
  18994. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18995. /**
  18996. * Specular produces a highlight color on an object.
  18997. * Note: This is note affecting PBR materials.
  18998. */
  18999. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19000. /**
  19001. * Strength of the light.
  19002. * Note: By default it is define in the framework own unit.
  19003. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19004. */
  19005. _this.intensity = 1.0;
  19006. /**
  19007. * Defines how far from the source the light is impacting in scene units.
  19008. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19009. */
  19010. _this.range = Number.MAX_VALUE;
  19011. /**
  19012. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19013. * of light.
  19014. */
  19015. _this._photometricScale = 1.0;
  19016. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19017. _this._radius = 0.00001;
  19018. /**
  19019. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19020. * exceeding the number allowed of the materials.
  19021. */
  19022. _this.renderPriority = 0;
  19023. /**
  19024. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19025. * the current shadow generator.
  19026. */
  19027. _this.shadowEnabled = true;
  19028. _this._excludeWithLayerMask = 0;
  19029. _this._includeOnlyWithLayerMask = 0;
  19030. _this._lightmapMode = 0;
  19031. /**
  19032. * @ignore Internal use only.
  19033. */
  19034. _this._excludedMeshesIds = new Array();
  19035. /**
  19036. * @ignore Internal use only.
  19037. */
  19038. _this._includedOnlyMeshesIds = new Array();
  19039. _this.getScene().addLight(_this);
  19040. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19041. _this._buildUniformLayout();
  19042. _this.includedOnlyMeshes = new Array();
  19043. _this.excludedMeshes = new Array();
  19044. _this._resyncMeshes();
  19045. return _this;
  19046. }
  19047. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19048. /**
  19049. * If every light affecting the material is in this lightmapMode,
  19050. * material.lightmapTexture adds or multiplies
  19051. * (depends on material.useLightmapAsShadowmap)
  19052. * after every other light calculations.
  19053. */
  19054. get: function () {
  19055. return Light._LIGHTMAP_DEFAULT;
  19056. },
  19057. enumerable: true,
  19058. configurable: true
  19059. });
  19060. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19061. /**
  19062. * material.lightmapTexture as only diffuse lighting from this light
  19063. * adds only specular lighting from this light
  19064. * adds dynamic shadows
  19065. */
  19066. get: function () {
  19067. return Light._LIGHTMAP_SPECULAR;
  19068. },
  19069. enumerable: true,
  19070. configurable: true
  19071. });
  19072. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19073. /**
  19074. * material.lightmapTexture as only lighting
  19075. * no light calculation from this light
  19076. * only adds dynamic shadows from this light
  19077. */
  19078. get: function () {
  19079. return Light._LIGHTMAP_SHADOWSONLY;
  19080. },
  19081. enumerable: true,
  19082. configurable: true
  19083. });
  19084. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19085. /**
  19086. * Each light type uses the default quantity according to its type:
  19087. * point/spot lights use luminous intensity
  19088. * directional lights use illuminance
  19089. */
  19090. get: function () {
  19091. return Light._INTENSITYMODE_AUTOMATIC;
  19092. },
  19093. enumerable: true,
  19094. configurable: true
  19095. });
  19096. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19097. /**
  19098. * lumen (lm)
  19099. */
  19100. get: function () {
  19101. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19102. },
  19103. enumerable: true,
  19104. configurable: true
  19105. });
  19106. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19107. /**
  19108. * candela (lm/sr)
  19109. */
  19110. get: function () {
  19111. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19112. },
  19113. enumerable: true,
  19114. configurable: true
  19115. });
  19116. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19117. /**
  19118. * lux (lm/m^2)
  19119. */
  19120. get: function () {
  19121. return Light._INTENSITYMODE_ILLUMINANCE;
  19122. },
  19123. enumerable: true,
  19124. configurable: true
  19125. });
  19126. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19127. /**
  19128. * nit (cd/m^2)
  19129. */
  19130. get: function () {
  19131. return Light._INTENSITYMODE_LUMINANCE;
  19132. },
  19133. enumerable: true,
  19134. configurable: true
  19135. });
  19136. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19137. /**
  19138. * Light type const id of the point light.
  19139. */
  19140. get: function () {
  19141. return Light._LIGHTTYPEID_POINTLIGHT;
  19142. },
  19143. enumerable: true,
  19144. configurable: true
  19145. });
  19146. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19147. /**
  19148. * Light type const id of the directional light.
  19149. */
  19150. get: function () {
  19151. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19152. },
  19153. enumerable: true,
  19154. configurable: true
  19155. });
  19156. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19157. /**
  19158. * Light type const id of the spot light.
  19159. */
  19160. get: function () {
  19161. return Light._LIGHTTYPEID_SPOTLIGHT;
  19162. },
  19163. enumerable: true,
  19164. configurable: true
  19165. });
  19166. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19167. /**
  19168. * Light type const id of the hemispheric light.
  19169. */
  19170. get: function () {
  19171. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19172. },
  19173. enumerable: true,
  19174. configurable: true
  19175. });
  19176. Object.defineProperty(Light.prototype, "intensityMode", {
  19177. /**
  19178. * Gets the photometric scale used to interpret the intensity.
  19179. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19180. */
  19181. get: function () {
  19182. return this._intensityMode;
  19183. },
  19184. /**
  19185. * Sets the photometric scale used to interpret the intensity.
  19186. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19187. */
  19188. set: function (value) {
  19189. this._intensityMode = value;
  19190. this._computePhotometricScale();
  19191. },
  19192. enumerable: true,
  19193. configurable: true
  19194. });
  19195. ;
  19196. ;
  19197. Object.defineProperty(Light.prototype, "radius", {
  19198. /**
  19199. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19200. */
  19201. get: function () {
  19202. return this._radius;
  19203. },
  19204. /**
  19205. * sets the light radius used by PBR Materials to simulate soft area lights.
  19206. */
  19207. set: function (value) {
  19208. this._radius = value;
  19209. this._computePhotometricScale();
  19210. },
  19211. enumerable: true,
  19212. configurable: true
  19213. });
  19214. ;
  19215. ;
  19216. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19217. /**
  19218. * Gets the only meshes impacted by this light.
  19219. */
  19220. get: function () {
  19221. return this._includedOnlyMeshes;
  19222. },
  19223. /**
  19224. * Sets the only meshes impacted by this light.
  19225. */
  19226. set: function (value) {
  19227. this._includedOnlyMeshes = value;
  19228. this._hookArrayForIncludedOnly(value);
  19229. },
  19230. enumerable: true,
  19231. configurable: true
  19232. });
  19233. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19234. /**
  19235. * Gets the meshes not impacted by this light.
  19236. */
  19237. get: function () {
  19238. return this._excludedMeshes;
  19239. },
  19240. /**
  19241. * Sets the meshes not impacted by this light.
  19242. */
  19243. set: function (value) {
  19244. this._excludedMeshes = value;
  19245. this._hookArrayForExcluded(value);
  19246. },
  19247. enumerable: true,
  19248. configurable: true
  19249. });
  19250. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19251. /**
  19252. * Gets the layer id use to find what meshes are not impacted by the light.
  19253. * Inactive if 0
  19254. */
  19255. get: function () {
  19256. return this._excludeWithLayerMask;
  19257. },
  19258. /**
  19259. * Sets the layer id use to find what meshes are not impacted by the light.
  19260. * Inactive if 0
  19261. */
  19262. set: function (value) {
  19263. this._excludeWithLayerMask = value;
  19264. this._resyncMeshes();
  19265. },
  19266. enumerable: true,
  19267. configurable: true
  19268. });
  19269. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19270. /**
  19271. * Gets the layer id use to find what meshes are impacted by the light.
  19272. * Inactive if 0
  19273. */
  19274. get: function () {
  19275. return this._includeOnlyWithLayerMask;
  19276. },
  19277. /**
  19278. * Sets the layer id use to find what meshes are impacted by the light.
  19279. * Inactive if 0
  19280. */
  19281. set: function (value) {
  19282. this._includeOnlyWithLayerMask = value;
  19283. this._resyncMeshes();
  19284. },
  19285. enumerable: true,
  19286. configurable: true
  19287. });
  19288. Object.defineProperty(Light.prototype, "lightmapMode", {
  19289. /**
  19290. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19291. */
  19292. get: function () {
  19293. return this._lightmapMode;
  19294. },
  19295. /**
  19296. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19297. */
  19298. set: function (value) {
  19299. if (this._lightmapMode === value) {
  19300. return;
  19301. }
  19302. this._lightmapMode = value;
  19303. this._markMeshesAsLightDirty();
  19304. },
  19305. enumerable: true,
  19306. configurable: true
  19307. });
  19308. /**
  19309. * Returns the string "Light".
  19310. * @returns the class name
  19311. */
  19312. Light.prototype.getClassName = function () {
  19313. return "Light";
  19314. };
  19315. /**
  19316. * Converts the light information to a readable string for debug purpose.
  19317. * @param fullDetails Supports for multiple levels of logging within scene loading
  19318. * @returns the human readable light info
  19319. */
  19320. Light.prototype.toString = function (fullDetails) {
  19321. var ret = "Name: " + this.name;
  19322. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19323. if (this.animations) {
  19324. for (var i = 0; i < this.animations.length; i++) {
  19325. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19326. }
  19327. }
  19328. if (fullDetails) {
  19329. }
  19330. return ret;
  19331. };
  19332. /**
  19333. * Set the enabled state of this node.
  19334. * @param value - the new enabled state
  19335. * @see isEnabled
  19336. */
  19337. Light.prototype.setEnabled = function (value) {
  19338. _super.prototype.setEnabled.call(this, value);
  19339. this._resyncMeshes();
  19340. };
  19341. /**
  19342. * Returns the Light associated shadow generator if any.
  19343. * @return the associated shadow generator.
  19344. */
  19345. Light.prototype.getShadowGenerator = function () {
  19346. return this._shadowGenerator;
  19347. };
  19348. /**
  19349. * Returns a Vector3, the absolute light position in the World.
  19350. * @returns the world space position of the light
  19351. */
  19352. Light.prototype.getAbsolutePosition = function () {
  19353. return BABYLON.Vector3.Zero();
  19354. };
  19355. /**
  19356. * Specifies if the light will affect the passed mesh.
  19357. * @param mesh The mesh to test against the light
  19358. * @return true the mesh is affected otherwise, false.
  19359. */
  19360. Light.prototype.canAffectMesh = function (mesh) {
  19361. if (!mesh) {
  19362. return true;
  19363. }
  19364. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19365. return false;
  19366. }
  19367. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19368. return false;
  19369. }
  19370. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19371. return false;
  19372. }
  19373. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19374. return false;
  19375. }
  19376. return true;
  19377. };
  19378. /**
  19379. * Computes and Returns the light World matrix.
  19380. * @returns the world matrix
  19381. */
  19382. Light.prototype.getWorldMatrix = function () {
  19383. this._currentRenderId = this.getScene().getRenderId();
  19384. var worldMatrix = this._getWorldMatrix();
  19385. if (this.parent && this.parent.getWorldMatrix) {
  19386. if (!this._parentedWorldMatrix) {
  19387. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19388. }
  19389. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19390. this._markSyncedWithParent();
  19391. return this._parentedWorldMatrix;
  19392. }
  19393. return worldMatrix;
  19394. };
  19395. /**
  19396. * Sort function to order lights for rendering.
  19397. * @param a First Light object to compare to second.
  19398. * @param b Second Light object to compare first.
  19399. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19400. */
  19401. Light.CompareLightsPriority = function (a, b) {
  19402. //shadow-casting lights have priority over non-shadow-casting lights
  19403. //the renderPrioirty is a secondary sort criterion
  19404. if (a.shadowEnabled !== b.shadowEnabled) {
  19405. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19406. }
  19407. return b.renderPriority - a.renderPriority;
  19408. };
  19409. /**
  19410. * Releases resources associated with this node.
  19411. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19412. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19413. */
  19414. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19415. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19416. if (this._shadowGenerator) {
  19417. this._shadowGenerator.dispose();
  19418. this._shadowGenerator = null;
  19419. }
  19420. // Animations
  19421. this.getScene().stopAnimation(this);
  19422. // Remove from meshes
  19423. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19424. var mesh = _a[_i];
  19425. mesh._removeLightSource(this);
  19426. }
  19427. this._uniformBuffer.dispose();
  19428. // Remove from scene
  19429. this.getScene().removeLight(this);
  19430. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19431. };
  19432. /**
  19433. * Returns the light type ID (integer).
  19434. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19435. */
  19436. Light.prototype.getTypeID = function () {
  19437. return 0;
  19438. };
  19439. /**
  19440. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19441. * @returns the scaled intensity in intensity mode unit
  19442. */
  19443. Light.prototype.getScaledIntensity = function () {
  19444. return this._photometricScale * this.intensity;
  19445. };
  19446. /**
  19447. * Returns a new Light object, named "name", from the current one.
  19448. * @param name The name of the cloned light
  19449. * @returns the new created light
  19450. */
  19451. Light.prototype.clone = function (name) {
  19452. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19453. if (!constructor) {
  19454. return null;
  19455. }
  19456. return BABYLON.SerializationHelper.Clone(constructor, this);
  19457. };
  19458. /**
  19459. * Serializes the current light into a Serialization object.
  19460. * @returns the serialized object.
  19461. */
  19462. Light.prototype.serialize = function () {
  19463. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19464. // Type
  19465. serializationObject.type = this.getTypeID();
  19466. // Parent
  19467. if (this.parent) {
  19468. serializationObject.parentId = this.parent.id;
  19469. }
  19470. // Inclusion / exclusions
  19471. if (this.excludedMeshes.length > 0) {
  19472. serializationObject.excludedMeshesIds = [];
  19473. this.excludedMeshes.forEach(function (mesh) {
  19474. serializationObject.excludedMeshesIds.push(mesh.id);
  19475. });
  19476. }
  19477. if (this.includedOnlyMeshes.length > 0) {
  19478. serializationObject.includedOnlyMeshesIds = [];
  19479. this.includedOnlyMeshes.forEach(function (mesh) {
  19480. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19481. });
  19482. }
  19483. // Animations
  19484. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19485. serializationObject.ranges = this.serializeAnimationRanges();
  19486. return serializationObject;
  19487. };
  19488. /**
  19489. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19490. * This new light is named "name" and added to the passed scene.
  19491. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19492. * @param name The friendly name of the light
  19493. * @param scene The scene the new light will belong to
  19494. * @returns the constructor function
  19495. */
  19496. Light.GetConstructorFromName = function (type, name, scene) {
  19497. switch (type) {
  19498. case 0:
  19499. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19500. case 1:
  19501. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19502. case 2:
  19503. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19504. case 3:
  19505. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19506. }
  19507. return null;
  19508. };
  19509. /**
  19510. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19511. * @param parsedLight The JSON representation of the light
  19512. * @param scene The scene to create the parsed light in
  19513. * @returns the created light after parsing
  19514. */
  19515. Light.Parse = function (parsedLight, scene) {
  19516. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19517. if (!constructor) {
  19518. return null;
  19519. }
  19520. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19521. // Inclusion / exclusions
  19522. if (parsedLight.excludedMeshesIds) {
  19523. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19524. }
  19525. if (parsedLight.includedOnlyMeshesIds) {
  19526. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19527. }
  19528. // Parent
  19529. if (parsedLight.parentId) {
  19530. light._waitingParentId = parsedLight.parentId;
  19531. }
  19532. // Animations
  19533. if (parsedLight.animations) {
  19534. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19535. var parsedAnimation = parsedLight.animations[animationIndex];
  19536. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19537. }
  19538. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19539. }
  19540. if (parsedLight.autoAnimate) {
  19541. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19542. }
  19543. return light;
  19544. };
  19545. Light.prototype._hookArrayForExcluded = function (array) {
  19546. var _this = this;
  19547. var oldPush = array.push;
  19548. array.push = function () {
  19549. var items = [];
  19550. for (var _i = 0; _i < arguments.length; _i++) {
  19551. items[_i] = arguments[_i];
  19552. }
  19553. var result = oldPush.apply(array, items);
  19554. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19555. var item = items_1[_a];
  19556. item._resyncLighSource(_this);
  19557. }
  19558. return result;
  19559. };
  19560. var oldSplice = array.splice;
  19561. array.splice = function (index, deleteCount) {
  19562. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19563. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19564. var item = deleted_1[_i];
  19565. item._resyncLighSource(_this);
  19566. }
  19567. return deleted;
  19568. };
  19569. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19570. var item = array_1[_i];
  19571. item._resyncLighSource(this);
  19572. }
  19573. };
  19574. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19575. var _this = this;
  19576. var oldPush = array.push;
  19577. array.push = function () {
  19578. var items = [];
  19579. for (var _i = 0; _i < arguments.length; _i++) {
  19580. items[_i] = arguments[_i];
  19581. }
  19582. var result = oldPush.apply(array, items);
  19583. _this._resyncMeshes();
  19584. return result;
  19585. };
  19586. var oldSplice = array.splice;
  19587. array.splice = function (index, deleteCount) {
  19588. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19589. _this._resyncMeshes();
  19590. return deleted;
  19591. };
  19592. this._resyncMeshes();
  19593. };
  19594. Light.prototype._resyncMeshes = function () {
  19595. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19596. var mesh = _a[_i];
  19597. mesh._resyncLighSource(this);
  19598. }
  19599. };
  19600. /**
  19601. * Forces the meshes to update their light related information in their rendering used effects
  19602. * @ignore Internal Use Only
  19603. */
  19604. Light.prototype._markMeshesAsLightDirty = function () {
  19605. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19606. var mesh = _a[_i];
  19607. if (mesh._lightSources.indexOf(this) !== -1) {
  19608. mesh._markSubMeshesAsLightDirty();
  19609. }
  19610. }
  19611. };
  19612. /**
  19613. * Recomputes the cached photometric scale if needed.
  19614. */
  19615. Light.prototype._computePhotometricScale = function () {
  19616. this._photometricScale = this._getPhotometricScale();
  19617. this.getScene().resetCachedMaterial();
  19618. };
  19619. /**
  19620. * Returns the Photometric Scale according to the light type and intensity mode.
  19621. */
  19622. Light.prototype._getPhotometricScale = function () {
  19623. var photometricScale = 0.0;
  19624. var lightTypeID = this.getTypeID();
  19625. //get photometric mode
  19626. var photometricMode = this.intensityMode;
  19627. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19628. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19629. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19630. }
  19631. else {
  19632. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19633. }
  19634. }
  19635. //compute photometric scale
  19636. switch (lightTypeID) {
  19637. case Light.LIGHTTYPEID_POINTLIGHT:
  19638. case Light.LIGHTTYPEID_SPOTLIGHT:
  19639. switch (photometricMode) {
  19640. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19641. photometricScale = 1.0 / (4.0 * Math.PI);
  19642. break;
  19643. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19644. photometricScale = 1.0;
  19645. break;
  19646. case Light.INTENSITYMODE_LUMINANCE:
  19647. photometricScale = this.radius * this.radius;
  19648. break;
  19649. }
  19650. break;
  19651. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19652. switch (photometricMode) {
  19653. case Light.INTENSITYMODE_ILLUMINANCE:
  19654. photometricScale = 1.0;
  19655. break;
  19656. case Light.INTENSITYMODE_LUMINANCE:
  19657. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19658. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19659. var apexAngleRadians = this.radius;
  19660. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19661. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19662. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19663. photometricScale = solidAngle;
  19664. break;
  19665. }
  19666. break;
  19667. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19668. // No fall off in hemisperic light.
  19669. photometricScale = 1.0;
  19670. break;
  19671. }
  19672. return photometricScale;
  19673. };
  19674. /**
  19675. * Reorder the light in the scene according to their defined priority.
  19676. * @ignore Internal Use Only
  19677. */
  19678. Light.prototype._reorderLightsInScene = function () {
  19679. var scene = this.getScene();
  19680. if (this._renderPriority != 0) {
  19681. scene.requireLightSorting = true;
  19682. }
  19683. this.getScene().sortLightsByPriority();
  19684. };
  19685. //lightmapMode Consts
  19686. Light._LIGHTMAP_DEFAULT = 0;
  19687. Light._LIGHTMAP_SPECULAR = 1;
  19688. Light._LIGHTMAP_SHADOWSONLY = 2;
  19689. // Intensity Mode Consts
  19690. Light._INTENSITYMODE_AUTOMATIC = 0;
  19691. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19692. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19693. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19694. Light._INTENSITYMODE_LUMINANCE = 4;
  19695. // Light types ids const.
  19696. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19697. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19698. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19699. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19700. __decorate([
  19701. BABYLON.serializeAsColor3()
  19702. ], Light.prototype, "diffuse", void 0);
  19703. __decorate([
  19704. BABYLON.serializeAsColor3()
  19705. ], Light.prototype, "specular", void 0);
  19706. __decorate([
  19707. BABYLON.serialize()
  19708. ], Light.prototype, "intensity", void 0);
  19709. __decorate([
  19710. BABYLON.serialize()
  19711. ], Light.prototype, "range", void 0);
  19712. __decorate([
  19713. BABYLON.serialize()
  19714. ], Light.prototype, "intensityMode", null);
  19715. __decorate([
  19716. BABYLON.serialize()
  19717. ], Light.prototype, "radius", null);
  19718. __decorate([
  19719. BABYLON.serialize()
  19720. ], Light.prototype, "_renderPriority", void 0);
  19721. __decorate([
  19722. BABYLON.expandToProperty("_reorderLightsInScene")
  19723. ], Light.prototype, "renderPriority", void 0);
  19724. __decorate([
  19725. BABYLON.serialize()
  19726. ], Light.prototype, "shadowEnabled", void 0);
  19727. __decorate([
  19728. BABYLON.serialize("excludeWithLayerMask")
  19729. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19730. __decorate([
  19731. BABYLON.serialize("includeOnlyWithLayerMask")
  19732. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19733. __decorate([
  19734. BABYLON.serialize("lightmapMode")
  19735. ], Light.prototype, "_lightmapMode", void 0);
  19736. return Light;
  19737. }(BABYLON.Node));
  19738. BABYLON.Light = Light;
  19739. })(BABYLON || (BABYLON = {}));
  19740. //# sourceMappingURL=babylon.light.js.map
  19741. var BABYLON;
  19742. (function (BABYLON) {
  19743. var Camera = /** @class */ (function (_super) {
  19744. __extends(Camera, _super);
  19745. function Camera(name, position, scene) {
  19746. var _this = _super.call(this, name, scene) || this;
  19747. /**
  19748. * The vector the camera should consider as up.
  19749. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19750. */
  19751. _this.upVector = BABYLON.Vector3.Up();
  19752. _this.orthoLeft = null;
  19753. _this.orthoRight = null;
  19754. _this.orthoBottom = null;
  19755. _this.orthoTop = null;
  19756. /**
  19757. * FOV is set in Radians. (default is 0.8)
  19758. */
  19759. _this.fov = 0.8;
  19760. _this.minZ = 1;
  19761. _this.maxZ = 10000.0;
  19762. _this.inertia = 0.9;
  19763. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19764. _this.isIntermediate = false;
  19765. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19766. /**
  19767. * Restricts the camera to viewing objects with the same layerMask.
  19768. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19769. */
  19770. _this.layerMask = 0x0FFFFFFF;
  19771. /**
  19772. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19773. */
  19774. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19775. // Camera rig members
  19776. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19777. _this._rigCameras = new Array();
  19778. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19779. _this._skipRendering = false;
  19780. _this.customRenderTargets = new Array();
  19781. // Observables
  19782. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19783. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19784. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19785. _this.onRestoreStateObservable = new BABYLON.Observable();
  19786. // Cache
  19787. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19788. _this._projectionMatrix = new BABYLON.Matrix();
  19789. _this._doNotComputeProjectionMatrix = false;
  19790. _this._postProcesses = new Array();
  19791. _this._transformMatrix = BABYLON.Matrix.Zero();
  19792. _this._activeMeshes = new BABYLON.SmartArray(256);
  19793. _this._globalPosition = BABYLON.Vector3.Zero();
  19794. _this._refreshFrustumPlanes = true;
  19795. _this.getScene().addCamera(_this);
  19796. if (!_this.getScene().activeCamera) {
  19797. _this.getScene().activeCamera = _this;
  19798. }
  19799. _this.position = position;
  19800. return _this;
  19801. }
  19802. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19803. get: function () {
  19804. return Camera._PERSPECTIVE_CAMERA;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19810. get: function () {
  19811. return Camera._ORTHOGRAPHIC_CAMERA;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19817. /**
  19818. * This is the default FOV mode for perspective cameras.
  19819. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19820. *
  19821. */
  19822. get: function () {
  19823. return Camera._FOVMODE_VERTICAL_FIXED;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19829. /**
  19830. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19831. *
  19832. */
  19833. get: function () {
  19834. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19840. get: function () {
  19841. return Camera._RIG_MODE_NONE;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19847. get: function () {
  19848. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19854. get: function () {
  19855. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19861. get: function () {
  19862. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19868. get: function () {
  19869. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19875. get: function () {
  19876. return Camera._RIG_MODE_VR;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19882. get: function () {
  19883. return Camera._RIG_MODE_WEBVR;
  19884. },
  19885. enumerable: true,
  19886. configurable: true
  19887. });
  19888. /**
  19889. * Store current camera state (fov, position, etc..)
  19890. */
  19891. Camera.prototype.storeState = function () {
  19892. this._stateStored = true;
  19893. this._storedFov = this.fov;
  19894. return this;
  19895. };
  19896. /**
  19897. * Restores the camera state values if it has been stored. You must call storeState() first
  19898. */
  19899. Camera.prototype._restoreStateValues = function () {
  19900. if (!this._stateStored) {
  19901. return false;
  19902. }
  19903. this.fov = this._storedFov;
  19904. return true;
  19905. };
  19906. /**
  19907. * Restored camera state. You must call storeState() first
  19908. */
  19909. Camera.prototype.restoreState = function () {
  19910. if (this._restoreStateValues()) {
  19911. this.onRestoreStateObservable.notifyObservers(this);
  19912. return true;
  19913. }
  19914. return false;
  19915. };
  19916. Camera.prototype.getClassName = function () {
  19917. return "Camera";
  19918. };
  19919. /**
  19920. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19921. */
  19922. Camera.prototype.toString = function (fullDetails) {
  19923. var ret = "Name: " + this.name;
  19924. ret += ", type: " + this.getClassName();
  19925. if (this.animations) {
  19926. for (var i = 0; i < this.animations.length; i++) {
  19927. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19928. }
  19929. }
  19930. if (fullDetails) {
  19931. }
  19932. return ret;
  19933. };
  19934. Object.defineProperty(Camera.prototype, "globalPosition", {
  19935. get: function () {
  19936. return this._globalPosition;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Camera.prototype.getActiveMeshes = function () {
  19942. return this._activeMeshes;
  19943. };
  19944. Camera.prototype.isActiveMesh = function (mesh) {
  19945. return (this._activeMeshes.indexOf(mesh) !== -1);
  19946. };
  19947. //Cache
  19948. Camera.prototype._initCache = function () {
  19949. _super.prototype._initCache.call(this);
  19950. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19951. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19952. this._cache.mode = undefined;
  19953. this._cache.minZ = undefined;
  19954. this._cache.maxZ = undefined;
  19955. this._cache.fov = undefined;
  19956. this._cache.fovMode = undefined;
  19957. this._cache.aspectRatio = undefined;
  19958. this._cache.orthoLeft = undefined;
  19959. this._cache.orthoRight = undefined;
  19960. this._cache.orthoBottom = undefined;
  19961. this._cache.orthoTop = undefined;
  19962. this._cache.renderWidth = undefined;
  19963. this._cache.renderHeight = undefined;
  19964. };
  19965. Camera.prototype._updateCache = function (ignoreParentClass) {
  19966. if (!ignoreParentClass) {
  19967. _super.prototype._updateCache.call(this);
  19968. }
  19969. this._cache.position.copyFrom(this.position);
  19970. this._cache.upVector.copyFrom(this.upVector);
  19971. };
  19972. // Synchronized
  19973. Camera.prototype._isSynchronized = function () {
  19974. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19975. };
  19976. Camera.prototype._isSynchronizedViewMatrix = function () {
  19977. if (!_super.prototype._isSynchronized.call(this))
  19978. return false;
  19979. return this._cache.position.equals(this.position)
  19980. && this._cache.upVector.equals(this.upVector)
  19981. && this.isSynchronizedWithParent();
  19982. };
  19983. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19984. var check = this._cache.mode === this.mode
  19985. && this._cache.minZ === this.minZ
  19986. && this._cache.maxZ === this.maxZ;
  19987. if (!check) {
  19988. return false;
  19989. }
  19990. var engine = this.getEngine();
  19991. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19992. check = this._cache.fov === this.fov
  19993. && this._cache.fovMode === this.fovMode
  19994. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19995. }
  19996. else {
  19997. check = this._cache.orthoLeft === this.orthoLeft
  19998. && this._cache.orthoRight === this.orthoRight
  19999. && this._cache.orthoBottom === this.orthoBottom
  20000. && this._cache.orthoTop === this.orthoTop
  20001. && this._cache.renderWidth === engine.getRenderWidth()
  20002. && this._cache.renderHeight === engine.getRenderHeight();
  20003. }
  20004. return check;
  20005. };
  20006. // Controls
  20007. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20008. };
  20009. Camera.prototype.detachControl = function (element) {
  20010. };
  20011. Camera.prototype.update = function () {
  20012. this._checkInputs();
  20013. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20014. this._updateRigCameras();
  20015. }
  20016. };
  20017. Camera.prototype._checkInputs = function () {
  20018. this.onAfterCheckInputsObservable.notifyObservers(this);
  20019. };
  20020. Object.defineProperty(Camera.prototype, "rigCameras", {
  20021. get: function () {
  20022. return this._rigCameras;
  20023. },
  20024. enumerable: true,
  20025. configurable: true
  20026. });
  20027. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20028. get: function () {
  20029. return this._rigPostProcess;
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. /**
  20035. * Internal, gets the first post proces.
  20036. * @returns the first post process to be run on this camera.
  20037. */
  20038. Camera.prototype._getFirstPostProcess = function () {
  20039. for (var pp in this._postProcesses) {
  20040. if (this._postProcesses[pp] !== null) {
  20041. return this._postProcesses[pp];
  20042. }
  20043. }
  20044. return null;
  20045. };
  20046. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20047. // invalidate framebuffer
  20048. var firstPostProcess = this._getFirstPostProcess();
  20049. if (firstPostProcess) {
  20050. firstPostProcess.markTextureDirty();
  20051. }
  20052. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20053. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20054. var cam = this._rigCameras[i];
  20055. var rigPostProcess = cam._rigPostProcess;
  20056. // for VR rig, there does not have to be a post process
  20057. if (rigPostProcess) {
  20058. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20059. if (isPass) {
  20060. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20061. cam.isIntermediate = this._postProcesses.length === 0;
  20062. }
  20063. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20064. rigPostProcess.markTextureDirty();
  20065. }
  20066. else {
  20067. cam._postProcesses = this._postProcesses.slice(0);
  20068. }
  20069. }
  20070. };
  20071. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20072. if (insertAt === void 0) { insertAt = null; }
  20073. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20074. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20075. return 0;
  20076. }
  20077. if (insertAt == null || insertAt < 0) {
  20078. this._postProcesses.push(postProcess);
  20079. }
  20080. else if (this._postProcesses[insertAt] === null) {
  20081. this._postProcesses[insertAt] = postProcess;
  20082. }
  20083. else {
  20084. this._postProcesses.splice(insertAt, 0, postProcess);
  20085. }
  20086. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20087. return this._postProcesses.indexOf(postProcess);
  20088. };
  20089. Camera.prototype.detachPostProcess = function (postProcess) {
  20090. var idx = this._postProcesses.indexOf(postProcess);
  20091. if (idx !== -1) {
  20092. this._postProcesses[idx] = null;
  20093. }
  20094. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20095. };
  20096. Camera.prototype.getWorldMatrix = function () {
  20097. if (!this._worldMatrix) {
  20098. this._worldMatrix = BABYLON.Matrix.Identity();
  20099. }
  20100. var viewMatrix = this.getViewMatrix();
  20101. viewMatrix.invertToRef(this._worldMatrix);
  20102. return this._worldMatrix;
  20103. };
  20104. Camera.prototype._getViewMatrix = function () {
  20105. return BABYLON.Matrix.Identity();
  20106. };
  20107. Camera.prototype.getViewMatrix = function (force) {
  20108. if (!force && this._isSynchronizedViewMatrix()) {
  20109. return this._computedViewMatrix;
  20110. }
  20111. this.updateCache();
  20112. this._computedViewMatrix = this._getViewMatrix();
  20113. this._currentRenderId = this.getScene().getRenderId();
  20114. this._refreshFrustumPlanes = true;
  20115. if (!this.parent || !this.parent.getWorldMatrix) {
  20116. this._globalPosition.copyFrom(this.position);
  20117. }
  20118. else {
  20119. if (!this._worldMatrix) {
  20120. this._worldMatrix = BABYLON.Matrix.Identity();
  20121. }
  20122. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20123. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20124. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20125. this._computedViewMatrix.invert();
  20126. this._markSyncedWithParent();
  20127. }
  20128. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20129. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20130. }
  20131. this.onViewMatrixChangedObservable.notifyObservers(this);
  20132. return this._computedViewMatrix;
  20133. };
  20134. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20135. this._doNotComputeProjectionMatrix = true;
  20136. if (projection !== undefined) {
  20137. this._projectionMatrix = projection;
  20138. }
  20139. };
  20140. ;
  20141. Camera.prototype.unfreezeProjectionMatrix = function () {
  20142. this._doNotComputeProjectionMatrix = false;
  20143. };
  20144. ;
  20145. Camera.prototype.getProjectionMatrix = function (force) {
  20146. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20147. return this._projectionMatrix;
  20148. }
  20149. // Cache
  20150. this._cache.mode = this.mode;
  20151. this._cache.minZ = this.minZ;
  20152. this._cache.maxZ = this.maxZ;
  20153. // Matrix
  20154. this._refreshFrustumPlanes = true;
  20155. var engine = this.getEngine();
  20156. var scene = this.getScene();
  20157. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20158. this._cache.fov = this.fov;
  20159. this._cache.fovMode = this.fovMode;
  20160. this._cache.aspectRatio = engine.getAspectRatio(this);
  20161. if (this.minZ <= 0) {
  20162. this.minZ = 0.1;
  20163. }
  20164. if (scene.useRightHandedSystem) {
  20165. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20166. }
  20167. else {
  20168. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20169. }
  20170. }
  20171. else {
  20172. var halfWidth = engine.getRenderWidth() / 2.0;
  20173. var halfHeight = engine.getRenderHeight() / 2.0;
  20174. if (scene.useRightHandedSystem) {
  20175. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20176. }
  20177. else {
  20178. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20179. }
  20180. this._cache.orthoLeft = this.orthoLeft;
  20181. this._cache.orthoRight = this.orthoRight;
  20182. this._cache.orthoBottom = this.orthoBottom;
  20183. this._cache.orthoTop = this.orthoTop;
  20184. this._cache.renderWidth = engine.getRenderWidth();
  20185. this._cache.renderHeight = engine.getRenderHeight();
  20186. }
  20187. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20188. return this._projectionMatrix;
  20189. };
  20190. Camera.prototype.getTranformationMatrix = function () {
  20191. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20192. return this._transformMatrix;
  20193. };
  20194. Camera.prototype.updateFrustumPlanes = function () {
  20195. if (!this._refreshFrustumPlanes) {
  20196. return;
  20197. }
  20198. this.getTranformationMatrix();
  20199. if (!this._frustumPlanes) {
  20200. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20201. }
  20202. else {
  20203. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20204. }
  20205. this._refreshFrustumPlanes = false;
  20206. };
  20207. Camera.prototype.isInFrustum = function (target) {
  20208. this.updateFrustumPlanes();
  20209. return target.isInFrustum(this._frustumPlanes);
  20210. };
  20211. Camera.prototype.isCompletelyInFrustum = function (target) {
  20212. this.updateFrustumPlanes();
  20213. return target.isCompletelyInFrustum(this._frustumPlanes);
  20214. };
  20215. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20216. if (length === void 0) { length = 100; }
  20217. if (!transform) {
  20218. transform = this.getWorldMatrix();
  20219. }
  20220. if (!origin) {
  20221. origin = this.position;
  20222. }
  20223. var forward = new BABYLON.Vector3(0, 0, 1);
  20224. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20225. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20226. return new BABYLON.Ray(origin, direction, length);
  20227. };
  20228. /**
  20229. * Releases resources associated with this node.
  20230. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20231. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20232. */
  20233. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20234. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20235. // Observables
  20236. this.onViewMatrixChangedObservable.clear();
  20237. this.onProjectionMatrixChangedObservable.clear();
  20238. this.onAfterCheckInputsObservable.clear();
  20239. this.onRestoreStateObservable.clear();
  20240. // Inputs
  20241. if (this.inputs) {
  20242. this.inputs.clear();
  20243. }
  20244. // Animations
  20245. this.getScene().stopAnimation(this);
  20246. // Remove from scene
  20247. this.getScene().removeCamera(this);
  20248. while (this._rigCameras.length > 0) {
  20249. var camera = this._rigCameras.pop();
  20250. if (camera) {
  20251. camera.dispose();
  20252. }
  20253. }
  20254. // Postprocesses
  20255. if (this._rigPostProcess) {
  20256. this._rigPostProcess.dispose(this);
  20257. this._rigPostProcess = null;
  20258. this._postProcesses = [];
  20259. }
  20260. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20261. this._rigPostProcess = null;
  20262. this._postProcesses = [];
  20263. }
  20264. else {
  20265. var i = this._postProcesses.length;
  20266. while (--i >= 0) {
  20267. var postProcess = this._postProcesses[i];
  20268. if (postProcess) {
  20269. postProcess.dispose(this);
  20270. }
  20271. }
  20272. }
  20273. // Render targets
  20274. var i = this.customRenderTargets.length;
  20275. while (--i >= 0) {
  20276. this.customRenderTargets[i].dispose();
  20277. }
  20278. this.customRenderTargets = [];
  20279. // Active Meshes
  20280. this._activeMeshes.dispose();
  20281. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20282. };
  20283. Object.defineProperty(Camera.prototype, "leftCamera", {
  20284. // ---- Camera rigs section ----
  20285. get: function () {
  20286. if (this._rigCameras.length < 1) {
  20287. return null;
  20288. }
  20289. return this._rigCameras[0];
  20290. },
  20291. enumerable: true,
  20292. configurable: true
  20293. });
  20294. Object.defineProperty(Camera.prototype, "rightCamera", {
  20295. get: function () {
  20296. if (this._rigCameras.length < 2) {
  20297. return null;
  20298. }
  20299. return this._rigCameras[1];
  20300. },
  20301. enumerable: true,
  20302. configurable: true
  20303. });
  20304. Camera.prototype.getLeftTarget = function () {
  20305. if (this._rigCameras.length < 1) {
  20306. return null;
  20307. }
  20308. return this._rigCameras[0].getTarget();
  20309. };
  20310. Camera.prototype.getRightTarget = function () {
  20311. if (this._rigCameras.length < 2) {
  20312. return null;
  20313. }
  20314. return this._rigCameras[1].getTarget();
  20315. };
  20316. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20317. if (this.cameraRigMode === mode) {
  20318. return;
  20319. }
  20320. while (this._rigCameras.length > 0) {
  20321. var camera = this._rigCameras.pop();
  20322. if (camera) {
  20323. camera.dispose();
  20324. }
  20325. }
  20326. this.cameraRigMode = mode;
  20327. this._cameraRigParams = {};
  20328. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20329. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20330. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20331. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20332. // create the rig cameras, unless none
  20333. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20334. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20335. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20336. if (leftCamera && rightCamera) {
  20337. this._rigCameras.push(leftCamera);
  20338. this._rigCameras.push(rightCamera);
  20339. }
  20340. }
  20341. switch (this.cameraRigMode) {
  20342. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20343. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20344. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20345. break;
  20346. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20347. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20348. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20349. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20350. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20351. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20352. break;
  20353. case Camera.RIG_MODE_VR:
  20354. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20355. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20356. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20357. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20358. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20359. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20360. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20361. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20362. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20363. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20364. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20365. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20366. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20367. if (metrics.compensateDistortion) {
  20368. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20369. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20370. }
  20371. break;
  20372. case Camera.RIG_MODE_WEBVR:
  20373. if (rigParams.vrDisplay) {
  20374. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20375. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20376. //Left eye
  20377. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20378. this._rigCameras[0].setCameraRigParameter("left", true);
  20379. //leaving this for future reference
  20380. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20381. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20382. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20383. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20384. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20385. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20386. this._rigCameras[0].parent = this;
  20387. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20388. //Right eye
  20389. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20390. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20391. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20392. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20393. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20394. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20395. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20396. this._rigCameras[1].parent = this;
  20397. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20398. if (Camera.UseAlternateWebVRRendering) {
  20399. this._rigCameras[1]._skipRendering = true;
  20400. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20401. }
  20402. }
  20403. break;
  20404. }
  20405. this._cascadePostProcessesToRigCams();
  20406. this.update();
  20407. };
  20408. Camera.prototype._getVRProjectionMatrix = function () {
  20409. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20410. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20411. return this._projectionMatrix;
  20412. };
  20413. Camera.prototype._updateCameraRotationMatrix = function () {
  20414. //Here for WebVR
  20415. };
  20416. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20417. //Here for WebVR
  20418. };
  20419. /**
  20420. * This function MUST be overwritten by the different WebVR cameras available.
  20421. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20422. */
  20423. Camera.prototype._getWebVRProjectionMatrix = function () {
  20424. return BABYLON.Matrix.Identity();
  20425. };
  20426. /**
  20427. * This function MUST be overwritten by the different WebVR cameras available.
  20428. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20429. */
  20430. Camera.prototype._getWebVRViewMatrix = function () {
  20431. return BABYLON.Matrix.Identity();
  20432. };
  20433. Camera.prototype.setCameraRigParameter = function (name, value) {
  20434. if (!this._cameraRigParams) {
  20435. this._cameraRigParams = {};
  20436. }
  20437. this._cameraRigParams[name] = value;
  20438. //provisionnally:
  20439. if (name === "interaxialDistance") {
  20440. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20441. }
  20442. };
  20443. /**
  20444. * needs to be overridden by children so sub has required properties to be copied
  20445. */
  20446. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20447. return null;
  20448. };
  20449. /**
  20450. * May need to be overridden by children
  20451. */
  20452. Camera.prototype._updateRigCameras = function () {
  20453. for (var i = 0; i < this._rigCameras.length; i++) {
  20454. this._rigCameras[i].minZ = this.minZ;
  20455. this._rigCameras[i].maxZ = this.maxZ;
  20456. this._rigCameras[i].fov = this.fov;
  20457. }
  20458. // only update viewport when ANAGLYPH
  20459. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20460. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20461. }
  20462. };
  20463. Camera.prototype._setupInputs = function () {
  20464. };
  20465. Camera.prototype.serialize = function () {
  20466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20467. // Type
  20468. serializationObject.type = this.getClassName();
  20469. // Parent
  20470. if (this.parent) {
  20471. serializationObject.parentId = this.parent.id;
  20472. }
  20473. if (this.inputs) {
  20474. this.inputs.serialize(serializationObject);
  20475. }
  20476. // Animations
  20477. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20478. serializationObject.ranges = this.serializeAnimationRanges();
  20479. return serializationObject;
  20480. };
  20481. Camera.prototype.clone = function (name) {
  20482. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20483. };
  20484. Camera.prototype.getDirection = function (localAxis) {
  20485. var result = BABYLON.Vector3.Zero();
  20486. this.getDirectionToRef(localAxis, result);
  20487. return result;
  20488. };
  20489. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20490. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20491. };
  20492. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20493. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20494. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20495. switch (type) {
  20496. case "ArcRotateCamera":
  20497. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20498. case "DeviceOrientationCamera":
  20499. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20500. case "FollowCamera":
  20501. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20502. case "ArcFollowCamera":
  20503. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20504. case "GamepadCamera":
  20505. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20506. case "TouchCamera":
  20507. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20508. case "VirtualJoysticksCamera":
  20509. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20510. case "WebVRFreeCamera":
  20511. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20512. case "WebVRGamepadCamera":
  20513. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20514. case "VRDeviceOrientationFreeCamera":
  20515. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20516. case "VRDeviceOrientationGamepadCamera":
  20517. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20518. case "AnaglyphArcRotateCamera":
  20519. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20520. case "AnaglyphFreeCamera":
  20521. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20522. case "AnaglyphGamepadCamera":
  20523. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20524. case "AnaglyphUniversalCamera":
  20525. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20526. case "StereoscopicArcRotateCamera":
  20527. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20528. case "StereoscopicFreeCamera":
  20529. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20530. case "StereoscopicGamepadCamera":
  20531. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20532. case "StereoscopicUniversalCamera":
  20533. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20534. case "FreeCamera":// Forcing Universal here
  20535. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20536. default:// Universal Camera is the default value
  20537. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20538. }
  20539. };
  20540. Camera.prototype.computeWorldMatrix = function () {
  20541. return this.getWorldMatrix();
  20542. };
  20543. Camera.Parse = function (parsedCamera, scene) {
  20544. var type = parsedCamera.type;
  20545. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20546. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20547. // Parent
  20548. if (parsedCamera.parentId) {
  20549. camera._waitingParentId = parsedCamera.parentId;
  20550. }
  20551. //If camera has an input manager, let it parse inputs settings
  20552. if (camera.inputs) {
  20553. camera.inputs.parse(parsedCamera);
  20554. camera._setupInputs();
  20555. }
  20556. if (camera.setPosition) {
  20557. camera.position.copyFromFloats(0, 0, 0);
  20558. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20559. }
  20560. // Target
  20561. if (parsedCamera.target) {
  20562. if (camera.setTarget) {
  20563. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20564. }
  20565. }
  20566. // Apply 3d rig, when found
  20567. if (parsedCamera.cameraRigMode) {
  20568. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20569. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20570. }
  20571. // Animations
  20572. if (parsedCamera.animations) {
  20573. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20574. var parsedAnimation = parsedCamera.animations[animationIndex];
  20575. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20576. }
  20577. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20578. }
  20579. if (parsedCamera.autoAnimate) {
  20580. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20581. }
  20582. return camera;
  20583. };
  20584. // Statics
  20585. Camera._PERSPECTIVE_CAMERA = 0;
  20586. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20587. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20588. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20589. Camera._RIG_MODE_NONE = 0;
  20590. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20591. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20592. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20593. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20594. Camera._RIG_MODE_VR = 20;
  20595. Camera._RIG_MODE_WEBVR = 21;
  20596. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20597. Camera.UseAlternateWebVRRendering = false;
  20598. __decorate([
  20599. BABYLON.serializeAsVector3()
  20600. ], Camera.prototype, "position", void 0);
  20601. __decorate([
  20602. BABYLON.serializeAsVector3()
  20603. ], Camera.prototype, "upVector", void 0);
  20604. __decorate([
  20605. BABYLON.serialize()
  20606. ], Camera.prototype, "orthoLeft", void 0);
  20607. __decorate([
  20608. BABYLON.serialize()
  20609. ], Camera.prototype, "orthoRight", void 0);
  20610. __decorate([
  20611. BABYLON.serialize()
  20612. ], Camera.prototype, "orthoBottom", void 0);
  20613. __decorate([
  20614. BABYLON.serialize()
  20615. ], Camera.prototype, "orthoTop", void 0);
  20616. __decorate([
  20617. BABYLON.serialize()
  20618. ], Camera.prototype, "fov", void 0);
  20619. __decorate([
  20620. BABYLON.serialize()
  20621. ], Camera.prototype, "minZ", void 0);
  20622. __decorate([
  20623. BABYLON.serialize()
  20624. ], Camera.prototype, "maxZ", void 0);
  20625. __decorate([
  20626. BABYLON.serialize()
  20627. ], Camera.prototype, "inertia", void 0);
  20628. __decorate([
  20629. BABYLON.serialize()
  20630. ], Camera.prototype, "mode", void 0);
  20631. __decorate([
  20632. BABYLON.serialize()
  20633. ], Camera.prototype, "layerMask", void 0);
  20634. __decorate([
  20635. BABYLON.serialize()
  20636. ], Camera.prototype, "fovMode", void 0);
  20637. __decorate([
  20638. BABYLON.serialize()
  20639. ], Camera.prototype, "cameraRigMode", void 0);
  20640. __decorate([
  20641. BABYLON.serialize()
  20642. ], Camera.prototype, "interaxialDistance", void 0);
  20643. __decorate([
  20644. BABYLON.serialize()
  20645. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20646. return Camera;
  20647. }(BABYLON.Node));
  20648. BABYLON.Camera = Camera;
  20649. })(BABYLON || (BABYLON = {}));
  20650. //# sourceMappingURL=babylon.camera.js.map
  20651. var BABYLON;
  20652. (function (BABYLON) {
  20653. var RenderingManager = /** @class */ (function () {
  20654. function RenderingManager(scene) {
  20655. this._renderingGroups = new Array();
  20656. this._autoClearDepthStencil = {};
  20657. this._customOpaqueSortCompareFn = {};
  20658. this._customAlphaTestSortCompareFn = {};
  20659. this._customTransparentSortCompareFn = {};
  20660. this._renderinGroupInfo = null;
  20661. this._scene = scene;
  20662. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20663. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20664. }
  20665. }
  20666. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20667. if (depth === void 0) { depth = true; }
  20668. if (stencil === void 0) { stencil = true; }
  20669. if (this._depthStencilBufferAlreadyCleaned) {
  20670. return;
  20671. }
  20672. this._scene.getEngine().clear(null, false, depth, stencil);
  20673. this._depthStencilBufferAlreadyCleaned = true;
  20674. };
  20675. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20676. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20677. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20678. var info = null;
  20679. if (observable) {
  20680. if (!this._renderinGroupInfo) {
  20681. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20682. }
  20683. info = this._renderinGroupInfo;
  20684. info.scene = this._scene;
  20685. info.camera = this._scene.activeCamera;
  20686. }
  20687. // Dispatch sprites
  20688. if (renderSprites) {
  20689. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20690. var manager = this._scene.spriteManagers[index];
  20691. this.dispatchSprites(manager);
  20692. }
  20693. }
  20694. // Render
  20695. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20696. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20697. var renderingGroup = this._renderingGroups[index];
  20698. if (!renderingGroup && !observable)
  20699. continue;
  20700. var renderingGroupMask = 0;
  20701. // Fire PRECLEAR stage
  20702. if (observable && info) {
  20703. renderingGroupMask = Math.pow(2, index);
  20704. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20705. info.renderingGroupId = index;
  20706. observable.notifyObservers(info, renderingGroupMask);
  20707. }
  20708. // Clear depth/stencil if needed
  20709. if (RenderingManager.AUTOCLEAR) {
  20710. var autoClear = this._autoClearDepthStencil[index];
  20711. if (autoClear && autoClear.autoClear) {
  20712. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20713. }
  20714. }
  20715. if (observable && info) {
  20716. // Fire PREOPAQUE stage
  20717. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20718. observable.notifyObservers(info, renderingGroupMask);
  20719. // Fire PRETRANSPARENT stage
  20720. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20721. observable.notifyObservers(info, renderingGroupMask);
  20722. }
  20723. if (renderingGroup)
  20724. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20725. // Fire POSTTRANSPARENT stage
  20726. if (observable && info) {
  20727. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20728. observable.notifyObservers(info, renderingGroupMask);
  20729. }
  20730. }
  20731. };
  20732. RenderingManager.prototype.reset = function () {
  20733. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20734. var renderingGroup = this._renderingGroups[index];
  20735. if (renderingGroup) {
  20736. renderingGroup.prepare();
  20737. }
  20738. }
  20739. };
  20740. RenderingManager.prototype.dispose = function () {
  20741. this.freeRenderingGroups();
  20742. this._renderingGroups.length = 0;
  20743. };
  20744. /**
  20745. * Clear the info related to rendering groups preventing retention points during dispose.
  20746. */
  20747. RenderingManager.prototype.freeRenderingGroups = function () {
  20748. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20749. var renderingGroup = this._renderingGroups[index];
  20750. if (renderingGroup) {
  20751. renderingGroup.dispose();
  20752. }
  20753. }
  20754. };
  20755. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20756. if (this._renderingGroups[renderingGroupId] === undefined) {
  20757. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20758. }
  20759. };
  20760. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20761. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20762. this._prepareRenderingGroup(renderingGroupId);
  20763. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20764. };
  20765. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20766. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20767. this._prepareRenderingGroup(renderingGroupId);
  20768. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20769. };
  20770. /**
  20771. * @param subMesh The submesh to dispatch
  20772. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20773. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20774. */
  20775. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20776. if (mesh === undefined) {
  20777. mesh = subMesh.getMesh();
  20778. }
  20779. var renderingGroupId = mesh.renderingGroupId || 0;
  20780. this._prepareRenderingGroup(renderingGroupId);
  20781. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20782. };
  20783. /**
  20784. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20785. * This allowed control for front to back rendering or reversly depending of the special needs.
  20786. *
  20787. * @param renderingGroupId The rendering group id corresponding to its index
  20788. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20789. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20790. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20791. */
  20792. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20793. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20794. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20795. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20796. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20797. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20798. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20799. if (this._renderingGroups[renderingGroupId]) {
  20800. var group = this._renderingGroups[renderingGroupId];
  20801. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20802. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20803. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20804. }
  20805. };
  20806. /**
  20807. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20808. *
  20809. * @param renderingGroupId The rendering group id corresponding to its index
  20810. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20811. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20812. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20813. */
  20814. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20815. if (depth === void 0) { depth = true; }
  20816. if (stencil === void 0) { stencil = true; }
  20817. this._autoClearDepthStencil[renderingGroupId] = {
  20818. autoClear: autoClearDepthStencil,
  20819. depth: depth,
  20820. stencil: stencil
  20821. };
  20822. };
  20823. /**
  20824. * The max id used for rendering groups (not included)
  20825. */
  20826. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20827. /**
  20828. * The min id used for rendering groups (included)
  20829. */
  20830. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20831. /**
  20832. * Used to globally prevent autoclearing scenes.
  20833. */
  20834. RenderingManager.AUTOCLEAR = true;
  20835. return RenderingManager;
  20836. }());
  20837. BABYLON.RenderingManager = RenderingManager;
  20838. })(BABYLON || (BABYLON = {}));
  20839. //# sourceMappingURL=babylon.renderingManager.js.map
  20840. var BABYLON;
  20841. (function (BABYLON) {
  20842. var RenderingGroup = /** @class */ (function () {
  20843. /**
  20844. * Creates a new rendering group.
  20845. * @param index The rendering group index
  20846. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20847. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20848. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20849. */
  20850. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20851. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20852. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20853. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20854. this.index = index;
  20855. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20856. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20857. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20858. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20859. this._particleSystems = new BABYLON.SmartArray(256);
  20860. this._spriteManagers = new BABYLON.SmartArray(256);
  20861. this._edgesRenderers = new BABYLON.SmartArray(16);
  20862. this._scene = scene;
  20863. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20864. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20865. this.transparentSortCompareFn = transparentSortCompareFn;
  20866. }
  20867. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20868. /**
  20869. * Set the opaque sort comparison function.
  20870. * If null the sub meshes will be render in the order they were created
  20871. */
  20872. set: function (value) {
  20873. this._opaqueSortCompareFn = value;
  20874. if (value) {
  20875. this._renderOpaque = this.renderOpaqueSorted;
  20876. }
  20877. else {
  20878. this._renderOpaque = RenderingGroup.renderUnsorted;
  20879. }
  20880. },
  20881. enumerable: true,
  20882. configurable: true
  20883. });
  20884. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20885. /**
  20886. * Set the alpha test sort comparison function.
  20887. * If null the sub meshes will be render in the order they were created
  20888. */
  20889. set: function (value) {
  20890. this._alphaTestSortCompareFn = value;
  20891. if (value) {
  20892. this._renderAlphaTest = this.renderAlphaTestSorted;
  20893. }
  20894. else {
  20895. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20896. }
  20897. },
  20898. enumerable: true,
  20899. configurable: true
  20900. });
  20901. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20902. /**
  20903. * Set the transparent sort comparison function.
  20904. * If null the sub meshes will be render in the order they were created
  20905. */
  20906. set: function (value) {
  20907. if (value) {
  20908. this._transparentSortCompareFn = value;
  20909. }
  20910. else {
  20911. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20912. }
  20913. this._renderTransparent = this.renderTransparentSorted;
  20914. },
  20915. enumerable: true,
  20916. configurable: true
  20917. });
  20918. /**
  20919. * Render all the sub meshes contained in the group.
  20920. * @param customRenderFunction Used to override the default render behaviour of the group.
  20921. * @returns true if rendered some submeshes.
  20922. */
  20923. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20924. if (customRenderFunction) {
  20925. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20926. return;
  20927. }
  20928. var engine = this._scene.getEngine();
  20929. // Depth only
  20930. if (this._depthOnlySubMeshes.length !== 0) {
  20931. engine.setColorWrite(false);
  20932. this._renderAlphaTest(this._depthOnlySubMeshes);
  20933. engine.setColorWrite(true);
  20934. }
  20935. // Opaque
  20936. if (this._opaqueSubMeshes.length !== 0) {
  20937. this._renderOpaque(this._opaqueSubMeshes);
  20938. }
  20939. // Alpha test
  20940. if (this._alphaTestSubMeshes.length !== 0) {
  20941. this._renderAlphaTest(this._alphaTestSubMeshes);
  20942. }
  20943. var stencilState = engine.getStencilBuffer();
  20944. engine.setStencilBuffer(false);
  20945. // Sprites
  20946. if (renderSprites) {
  20947. this._renderSprites();
  20948. }
  20949. // Particles
  20950. if (renderParticles) {
  20951. this._renderParticles(activeMeshes);
  20952. }
  20953. if (this.onBeforeTransparentRendering) {
  20954. this.onBeforeTransparentRendering();
  20955. }
  20956. // Transparent
  20957. if (this._transparentSubMeshes.length !== 0) {
  20958. this._renderTransparent(this._transparentSubMeshes);
  20959. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20960. }
  20961. // Set back stencil to false in case it changes before the edge renderer.
  20962. engine.setStencilBuffer(false);
  20963. // Edges
  20964. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20965. this._edgesRenderers.data[edgesRendererIndex].render();
  20966. }
  20967. // Restore Stencil state.
  20968. engine.setStencilBuffer(stencilState);
  20969. };
  20970. /**
  20971. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20972. * @param subMeshes The submeshes to render
  20973. */
  20974. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20975. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20976. };
  20977. /**
  20978. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20979. * @param subMeshes The submeshes to render
  20980. */
  20981. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20982. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20983. };
  20984. /**
  20985. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20986. * @param subMeshes The submeshes to render
  20987. */
  20988. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20989. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20990. };
  20991. /**
  20992. * Renders the submeshes in a specified order.
  20993. * @param subMeshes The submeshes to sort before render
  20994. * @param sortCompareFn The comparison function use to sort
  20995. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20996. * @param transparent Specifies to activate blending if true
  20997. */
  20998. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20999. var subIndex = 0;
  21000. var subMesh;
  21001. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21002. for (; subIndex < subMeshes.length; subIndex++) {
  21003. subMesh = subMeshes.data[subIndex];
  21004. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21005. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21006. }
  21007. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21008. if (sortCompareFn) {
  21009. sortedArray.sort(sortCompareFn);
  21010. }
  21011. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21012. subMesh = sortedArray[subIndex];
  21013. if (transparent) {
  21014. var material = subMesh.getMaterial();
  21015. if (material && material.needDepthPrePass) {
  21016. var engine = material.getScene().getEngine();
  21017. engine.setColorWrite(false);
  21018. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21019. subMesh.render(false);
  21020. engine.setColorWrite(true);
  21021. }
  21022. }
  21023. subMesh.render(transparent);
  21024. }
  21025. };
  21026. /**
  21027. * Renders the submeshes in the order they were dispatched (no sort applied).
  21028. * @param subMeshes The submeshes to render
  21029. */
  21030. RenderingGroup.renderUnsorted = function (subMeshes) {
  21031. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21032. var submesh = subMeshes.data[subIndex];
  21033. submesh.render(false);
  21034. }
  21035. };
  21036. /**
  21037. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21038. * are rendered back to front if in the same alpha index.
  21039. *
  21040. * @param a The first submesh
  21041. * @param b The second submesh
  21042. * @returns The result of the comparison
  21043. */
  21044. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21045. // Alpha index first
  21046. if (a._alphaIndex > b._alphaIndex) {
  21047. return 1;
  21048. }
  21049. if (a._alphaIndex < b._alphaIndex) {
  21050. return -1;
  21051. }
  21052. // Then distance to camera
  21053. return RenderingGroup.backToFrontSortCompare(a, b);
  21054. };
  21055. /**
  21056. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21057. * are rendered back to front.
  21058. *
  21059. * @param a The first submesh
  21060. * @param b The second submesh
  21061. * @returns The result of the comparison
  21062. */
  21063. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21064. // Then distance to camera
  21065. if (a._distanceToCamera < b._distanceToCamera) {
  21066. return 1;
  21067. }
  21068. if (a._distanceToCamera > b._distanceToCamera) {
  21069. return -1;
  21070. }
  21071. return 0;
  21072. };
  21073. /**
  21074. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21075. * are rendered front to back (prevent overdraw).
  21076. *
  21077. * @param a The first submesh
  21078. * @param b The second submesh
  21079. * @returns The result of the comparison
  21080. */
  21081. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21082. // Then distance to camera
  21083. if (a._distanceToCamera < b._distanceToCamera) {
  21084. return -1;
  21085. }
  21086. if (a._distanceToCamera > b._distanceToCamera) {
  21087. return 1;
  21088. }
  21089. return 0;
  21090. };
  21091. /**
  21092. * Resets the different lists of submeshes to prepare a new frame.
  21093. */
  21094. RenderingGroup.prototype.prepare = function () {
  21095. this._opaqueSubMeshes.reset();
  21096. this._transparentSubMeshes.reset();
  21097. this._alphaTestSubMeshes.reset();
  21098. this._depthOnlySubMeshes.reset();
  21099. this._particleSystems.reset();
  21100. this._spriteManagers.reset();
  21101. this._edgesRenderers.reset();
  21102. };
  21103. RenderingGroup.prototype.dispose = function () {
  21104. this._opaqueSubMeshes.dispose();
  21105. this._transparentSubMeshes.dispose();
  21106. this._alphaTestSubMeshes.dispose();
  21107. this._depthOnlySubMeshes.dispose();
  21108. this._particleSystems.dispose();
  21109. this._spriteManagers.dispose();
  21110. this._edgesRenderers.dispose();
  21111. };
  21112. /**
  21113. * Inserts the submesh in its correct queue depending on its material.
  21114. * @param subMesh The submesh to dispatch
  21115. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21116. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21117. */
  21118. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21119. // Get mesh and materials if not provided
  21120. if (mesh === undefined) {
  21121. mesh = subMesh.getMesh();
  21122. }
  21123. if (material === undefined) {
  21124. material = subMesh.getMaterial();
  21125. }
  21126. if (material === null || material === undefined) {
  21127. return;
  21128. }
  21129. if (material.needAlphaBlendingForMesh(mesh)) {
  21130. this._transparentSubMeshes.push(subMesh);
  21131. }
  21132. else if (material.needAlphaTesting()) {
  21133. if (material.needDepthPrePass) {
  21134. this._depthOnlySubMeshes.push(subMesh);
  21135. }
  21136. this._alphaTestSubMeshes.push(subMesh);
  21137. }
  21138. else {
  21139. if (material.needDepthPrePass) {
  21140. this._depthOnlySubMeshes.push(subMesh);
  21141. }
  21142. this._opaqueSubMeshes.push(subMesh); // Opaque
  21143. }
  21144. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21145. this._edgesRenderers.push(mesh._edgesRenderer);
  21146. }
  21147. };
  21148. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21149. this._spriteManagers.push(spriteManager);
  21150. };
  21151. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21152. this._particleSystems.push(particleSystem);
  21153. };
  21154. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21155. if (this._particleSystems.length === 0) {
  21156. return;
  21157. }
  21158. // Particles
  21159. var activeCamera = this._scene.activeCamera;
  21160. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21161. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21162. var particleSystem = this._particleSystems.data[particleIndex];
  21163. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21164. continue;
  21165. }
  21166. var emitter = particleSystem.emitter;
  21167. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21168. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21169. }
  21170. }
  21171. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21172. };
  21173. RenderingGroup.prototype._renderSprites = function () {
  21174. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21175. return;
  21176. }
  21177. // Sprites
  21178. var activeCamera = this._scene.activeCamera;
  21179. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21180. for (var id = 0; id < this._spriteManagers.length; id++) {
  21181. var spriteManager = this._spriteManagers.data[id];
  21182. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21183. spriteManager.render();
  21184. }
  21185. }
  21186. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21187. };
  21188. return RenderingGroup;
  21189. }());
  21190. BABYLON.RenderingGroup = RenderingGroup;
  21191. })(BABYLON || (BABYLON = {}));
  21192. //# sourceMappingURL=babylon.renderingGroup.js.map
  21193. var BABYLON;
  21194. (function (BABYLON) {
  21195. var ClickInfo = /** @class */ (function () {
  21196. function ClickInfo() {
  21197. this._singleClick = false;
  21198. this._doubleClick = false;
  21199. this._hasSwiped = false;
  21200. this._ignore = false;
  21201. }
  21202. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21203. get: function () {
  21204. return this._singleClick;
  21205. },
  21206. set: function (b) {
  21207. this._singleClick = b;
  21208. },
  21209. enumerable: true,
  21210. configurable: true
  21211. });
  21212. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21213. get: function () {
  21214. return this._doubleClick;
  21215. },
  21216. set: function (b) {
  21217. this._doubleClick = b;
  21218. },
  21219. enumerable: true,
  21220. configurable: true
  21221. });
  21222. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21223. get: function () {
  21224. return this._hasSwiped;
  21225. },
  21226. set: function (b) {
  21227. this._hasSwiped = b;
  21228. },
  21229. enumerable: true,
  21230. configurable: true
  21231. });
  21232. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21233. get: function () {
  21234. return this._ignore;
  21235. },
  21236. set: function (b) {
  21237. this._ignore = b;
  21238. },
  21239. enumerable: true,
  21240. configurable: true
  21241. });
  21242. return ClickInfo;
  21243. }());
  21244. /**
  21245. * This class is used by the onRenderingGroupObservable
  21246. */
  21247. var RenderingGroupInfo = /** @class */ (function () {
  21248. function RenderingGroupInfo() {
  21249. }
  21250. /**
  21251. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21252. * This stage will be fired no matter what
  21253. */
  21254. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21255. /**
  21256. * Called before opaque object are rendered.
  21257. * This stage will be fired only if there's 3D Opaque content to render
  21258. */
  21259. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21260. /**
  21261. * Called after the opaque objects are rendered and before the transparent ones
  21262. * This stage will be fired only if there's 3D transparent content to render
  21263. */
  21264. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21265. /**
  21266. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21267. * This stage will be fired no matter what
  21268. */
  21269. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21270. return RenderingGroupInfo;
  21271. }());
  21272. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21273. /**
  21274. * Represents a scene to be rendered by the engine.
  21275. * @see http://doc.babylonjs.com/page.php?p=21911
  21276. */
  21277. var Scene = /** @class */ (function () {
  21278. /**
  21279. * @constructor
  21280. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21281. */
  21282. function Scene(engine) {
  21283. // Members
  21284. this.autoClear = true;
  21285. this.autoClearDepthAndStencil = true;
  21286. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21287. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21288. this.forceWireframe = false;
  21289. this._forcePointsCloud = false;
  21290. this.forceShowBoundingBoxes = false;
  21291. this.animationsEnabled = true;
  21292. this.useConstantAnimationDeltaTime = false;
  21293. this.constantlyUpdateMeshUnderPointer = false;
  21294. this.hoverCursor = "pointer";
  21295. this.defaultCursor = "";
  21296. /**
  21297. * This is used to call preventDefault() on pointer down
  21298. * in order to block unwanted artifacts like system double clicks
  21299. */
  21300. this.preventDefaultOnPointerDown = true;
  21301. // Metadata
  21302. this.metadata = null;
  21303. /**
  21304. * An event triggered when the scene is disposed.
  21305. * @type {BABYLON.Observable}
  21306. */
  21307. this.onDisposeObservable = new BABYLON.Observable();
  21308. /**
  21309. * An event triggered before rendering the scene (right after animations and physics)
  21310. * @type {BABYLON.Observable}
  21311. */
  21312. this.onBeforeRenderObservable = new BABYLON.Observable();
  21313. /**
  21314. * An event triggered after rendering the scene
  21315. * @type {BABYLON.Observable}
  21316. */
  21317. this.onAfterRenderObservable = new BABYLON.Observable();
  21318. /**
  21319. * An event triggered before animating the scene
  21320. * @type {BABYLON.Observable}
  21321. */
  21322. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21323. /**
  21324. * An event triggered after animations processing
  21325. * @type {BABYLON.Observable}
  21326. */
  21327. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21328. /**
  21329. * An event triggered before draw calls are ready to be sent
  21330. * @type {BABYLON.Observable}
  21331. */
  21332. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21333. /**
  21334. * An event triggered after draw calls have been sent
  21335. * @type {BABYLON.Observable}
  21336. */
  21337. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21338. /**
  21339. * An event triggered when physic simulation is about to be run
  21340. * @type {BABYLON.Observable}
  21341. */
  21342. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21343. /**
  21344. * An event triggered when physic simulation has been done
  21345. * @type {BABYLON.Observable}
  21346. */
  21347. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21348. /**
  21349. * An event triggered when the scene is ready
  21350. * @type {BABYLON.Observable}
  21351. */
  21352. this.onReadyObservable = new BABYLON.Observable();
  21353. /**
  21354. * An event triggered before rendering a camera
  21355. * @type {BABYLON.Observable}
  21356. */
  21357. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21358. /**
  21359. * An event triggered after rendering a camera
  21360. * @type {BABYLON.Observable}
  21361. */
  21362. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21363. /**
  21364. * An event triggered when active meshes evaluation is about to start
  21365. * @type {BABYLON.Observable}
  21366. */
  21367. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21368. /**
  21369. * An event triggered when active meshes evaluation is done
  21370. * @type {BABYLON.Observable}
  21371. */
  21372. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21373. /**
  21374. * An event triggered when particles rendering is about to start
  21375. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21376. * @type {BABYLON.Observable}
  21377. */
  21378. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21379. /**
  21380. * An event triggered when particles rendering is done
  21381. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21382. * @type {BABYLON.Observable}
  21383. */
  21384. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21385. /**
  21386. * An event triggered when sprites rendering is about to start
  21387. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21388. * @type {BABYLON.Observable}
  21389. */
  21390. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21391. /**
  21392. * An event triggered when sprites rendering is done
  21393. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21394. * @type {BABYLON.Observable}
  21395. */
  21396. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21397. /**
  21398. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21399. * @type {BABYLON.Observable}
  21400. */
  21401. this.onDataLoadedObservable = new BABYLON.Observable();
  21402. /**
  21403. * An event triggered when a camera is created
  21404. * @type {BABYLON.Observable}
  21405. */
  21406. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21407. /**
  21408. * An event triggered when a camera is removed
  21409. * @type {BABYLON.Observable}
  21410. */
  21411. this.onCameraRemovedObservable = new BABYLON.Observable();
  21412. /**
  21413. * An event triggered when a light is created
  21414. * @type {BABYLON.Observable}
  21415. */
  21416. this.onNewLightAddedObservable = new BABYLON.Observable();
  21417. /**
  21418. * An event triggered when a light is removed
  21419. * @type {BABYLON.Observable}
  21420. */
  21421. this.onLightRemovedObservable = new BABYLON.Observable();
  21422. /**
  21423. * An event triggered when a geometry is created
  21424. * @type {BABYLON.Observable}
  21425. */
  21426. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21427. /**
  21428. * An event triggered when a geometry is removed
  21429. * @type {BABYLON.Observable}
  21430. */
  21431. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21432. /**
  21433. * An event triggered when a transform node is created
  21434. * @type {BABYLON.Observable}
  21435. */
  21436. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21437. /**
  21438. * An event triggered when a transform node is removed
  21439. * @type {BABYLON.Observable}
  21440. */
  21441. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21442. /**
  21443. * An event triggered when a mesh is created
  21444. * @type {BABYLON.Observable}
  21445. */
  21446. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21447. /**
  21448. * An event triggered when a mesh is removed
  21449. * @type {BABYLON.Observable}
  21450. */
  21451. this.onMeshRemovedObservable = new BABYLON.Observable();
  21452. /**
  21453. * An event triggered when render targets are about to be rendered
  21454. * Can happen multiple times per frame.
  21455. * @type {BABYLON.Observable}
  21456. */
  21457. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21458. /**
  21459. * An event triggered when render targets were rendered.
  21460. * Can happen multiple times per frame.
  21461. * @type {BABYLON.Observable}
  21462. */
  21463. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21464. /**
  21465. * An event triggered before calculating deterministic simulation step
  21466. * @type {BABYLON.Observable}
  21467. */
  21468. this.onBeforeStepObservable = new BABYLON.Observable();
  21469. /**
  21470. * An event triggered after calculating deterministic simulation step
  21471. * @type {BABYLON.Observable}
  21472. */
  21473. this.onAfterStepObservable = new BABYLON.Observable();
  21474. /**
  21475. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21476. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21477. * 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)
  21478. */
  21479. this.onRenderingGroupObservable = new BABYLON.Observable();
  21480. // Animations
  21481. this.animations = [];
  21482. /**
  21483. * 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).
  21484. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21485. */
  21486. this.onPrePointerObservable = new BABYLON.Observable();
  21487. /**
  21488. * Observable event triggered each time an input event is received from the rendering canvas
  21489. */
  21490. this.onPointerObservable = new BABYLON.Observable();
  21491. this._meshPickProceed = false;
  21492. this._currentPickResult = null;
  21493. this._previousPickResult = null;
  21494. this._totalPointersPressed = 0;
  21495. this._doubleClickOccured = false;
  21496. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21497. this.cameraToUseForPointers = null;
  21498. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21499. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21500. this._startingPointerTime = 0;
  21501. this._previousStartingPointerTime = 0;
  21502. // Deterministic lockstep
  21503. this._timeAccumulator = 0;
  21504. this._currentStepId = 0;
  21505. this._currentInternalStep = 0;
  21506. // Keyboard
  21507. /**
  21508. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21509. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21510. */
  21511. this.onPreKeyboardObservable = new BABYLON.Observable();
  21512. /**
  21513. * Observable event triggered each time an keyboard event is received from the hosting window
  21514. */
  21515. this.onKeyboardObservable = new BABYLON.Observable();
  21516. // Coordinate system
  21517. /**
  21518. * use right-handed coordinate system on this scene.
  21519. * @type {boolean}
  21520. */
  21521. this._useRightHandedSystem = false;
  21522. // Fog
  21523. this._fogEnabled = true;
  21524. this._fogMode = Scene.FOGMODE_NONE;
  21525. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21526. this.fogDensity = 0.1;
  21527. this.fogStart = 0;
  21528. this.fogEnd = 1000.0;
  21529. // Lights
  21530. /**
  21531. * is shadow enabled on this scene.
  21532. * @type {boolean}
  21533. */
  21534. this._shadowsEnabled = true;
  21535. /**
  21536. * is light enabled on this scene.
  21537. * @type {boolean}
  21538. */
  21539. this._lightsEnabled = true;
  21540. /**
  21541. * All of the lights added to this scene.
  21542. * @see BABYLON.Light
  21543. * @type {BABYLON.Light[]}
  21544. */
  21545. this.lights = new Array();
  21546. // Cameras
  21547. /** All of the cameras added to this scene. */
  21548. this.cameras = new Array();
  21549. /** All of the active cameras added to this scene. */
  21550. this.activeCameras = new Array();
  21551. // Meshes
  21552. /**
  21553. * All of the tranform nodes added to this scene.
  21554. * @see BABYLON.TransformNode
  21555. * @type {BABYLON.TransformNode[]}
  21556. */
  21557. this.transformNodes = new Array();
  21558. /**
  21559. * All of the (abstract) meshes added to this scene.
  21560. * @see BABYLON.AbstractMesh
  21561. * @type {BABYLON.AbstractMesh[]}
  21562. */
  21563. this.meshes = new Array();
  21564. /**
  21565. * All of the animation groups added to this scene.
  21566. * @see BABYLON.AnimationGroup
  21567. * @type {BABYLON.AnimationGroup[]}
  21568. */
  21569. this.animationGroups = new Array();
  21570. // Geometries
  21571. this._geometries = new Array();
  21572. this.materials = new Array();
  21573. this.multiMaterials = new Array();
  21574. // Textures
  21575. this._texturesEnabled = true;
  21576. this.textures = new Array();
  21577. // Particles
  21578. this.particlesEnabled = true;
  21579. this.particleSystems = new Array();
  21580. // Sprites
  21581. this.spritesEnabled = true;
  21582. this.spriteManagers = new Array();
  21583. /**
  21584. * The list of layers (background and foreground) of the scene.
  21585. */
  21586. this.layers = new Array();
  21587. /**
  21588. * The list of effect layers (highlights/glow) contained in the scene.
  21589. */
  21590. this.effectLayers = new Array();
  21591. // Skeletons
  21592. this._skeletonsEnabled = true;
  21593. this.skeletons = new Array();
  21594. // Morph targets
  21595. this.morphTargetManagers = new Array();
  21596. // Lens flares
  21597. this.lensFlaresEnabled = true;
  21598. this.lensFlareSystems = new Array();
  21599. // Collisions
  21600. this.collisionsEnabled = true;
  21601. /** Defines the gravity applied to this scene */
  21602. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21603. // Postprocesses
  21604. this.postProcesses = new Array();
  21605. this.postProcessesEnabled = true;
  21606. // Customs render targets
  21607. this.renderTargetsEnabled = true;
  21608. this.dumpNextRenderTargets = false;
  21609. this.customRenderTargets = new Array();
  21610. // Imported meshes
  21611. this.importedMeshesFiles = new Array();
  21612. // Probes
  21613. this.probesEnabled = true;
  21614. this.reflectionProbes = new Array();
  21615. this._actionManagers = new Array();
  21616. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21617. // Procedural textures
  21618. this.proceduralTexturesEnabled = true;
  21619. this._proceduralTextures = new Array();
  21620. this.soundTracks = new Array();
  21621. this._audioEnabled = true;
  21622. this._headphone = false;
  21623. // Performance counters
  21624. this._totalVertices = new BABYLON.PerfCounter();
  21625. this._activeIndices = new BABYLON.PerfCounter();
  21626. this._activeParticles = new BABYLON.PerfCounter();
  21627. this._activeBones = new BABYLON.PerfCounter();
  21628. this._animationTime = 0;
  21629. this.animationTimeScale = 1;
  21630. this._renderId = 0;
  21631. this._executeWhenReadyTimeoutId = -1;
  21632. this._intermediateRendering = false;
  21633. this._viewUpdateFlag = -1;
  21634. this._projectionUpdateFlag = -1;
  21635. this._alternateViewUpdateFlag = -1;
  21636. this._alternateProjectionUpdateFlag = -1;
  21637. this._toBeDisposed = new BABYLON.SmartArray(256);
  21638. this._activeRequests = new Array();
  21639. this._pendingData = new Array();
  21640. this._isDisposed = false;
  21641. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21642. this._activeMeshes = new BABYLON.SmartArray(256);
  21643. this._processedMaterials = new BABYLON.SmartArray(256);
  21644. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21645. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21646. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21647. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21648. this._activeAnimatables = new Array();
  21649. this._transformMatrix = BABYLON.Matrix.Zero();
  21650. this._useAlternateCameraConfiguration = false;
  21651. this._alternateRendering = false;
  21652. this.requireLightSorting = false;
  21653. this._depthRenderer = {};
  21654. this._activeMeshesFrozen = false;
  21655. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21656. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21657. this._engine.scenes.push(this);
  21658. this._uid = null;
  21659. this._renderingManager = new BABYLON.RenderingManager(this);
  21660. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21661. if (BABYLON.OutlineRenderer) {
  21662. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21663. }
  21664. if (BABYLON.Tools.IsWindowObjectExist()) {
  21665. this.attachControl();
  21666. }
  21667. //simplification queue
  21668. if (BABYLON.SimplificationQueue) {
  21669. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21670. }
  21671. //collision coordinator initialization. For now legacy per default.
  21672. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21673. // Uniform Buffer
  21674. this._createUbo();
  21675. // Default Image processing definition.
  21676. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21677. }
  21678. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21679. /** The fog is deactivated */
  21680. get: function () {
  21681. return Scene._FOGMODE_NONE;
  21682. },
  21683. enumerable: true,
  21684. configurable: true
  21685. });
  21686. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21687. /** The fog density is following an exponential function */
  21688. get: function () {
  21689. return Scene._FOGMODE_EXP;
  21690. },
  21691. enumerable: true,
  21692. configurable: true
  21693. });
  21694. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21695. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21696. get: function () {
  21697. return Scene._FOGMODE_EXP2;
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21703. /** The fog density is following a linear function. */
  21704. get: function () {
  21705. return Scene._FOGMODE_LINEAR;
  21706. },
  21707. enumerable: true,
  21708. configurable: true
  21709. });
  21710. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21711. /**
  21712. * Texture used in all pbr material as the reflection texture.
  21713. * As in the majority of the scene they are the same (exception for multi room and so on),
  21714. * this is easier to reference from here than from all the materials.
  21715. */
  21716. get: function () {
  21717. return this._environmentTexture;
  21718. },
  21719. /**
  21720. * Texture used in all pbr material as the reflection texture.
  21721. * As in the majority of the scene they are the same (exception for multi room and so on),
  21722. * this is easier to set here than in all the materials.
  21723. */
  21724. set: function (value) {
  21725. if (this._environmentTexture === value) {
  21726. return;
  21727. }
  21728. this._environmentTexture = value;
  21729. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21730. },
  21731. enumerable: true,
  21732. configurable: true
  21733. });
  21734. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21735. /**
  21736. * Default image processing configuration used either in the rendering
  21737. * Forward main pass or through the imageProcessingPostProcess if present.
  21738. * As in the majority of the scene they are the same (exception for multi camera),
  21739. * this is easier to reference from here than from all the materials and post process.
  21740. *
  21741. * No setter as we it is a shared configuration, you can set the values instead.
  21742. */
  21743. get: function () {
  21744. return this._imageProcessingConfiguration;
  21745. },
  21746. enumerable: true,
  21747. configurable: true
  21748. });
  21749. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21750. get: function () {
  21751. return this._forcePointsCloud;
  21752. },
  21753. set: function (value) {
  21754. if (this._forcePointsCloud === value) {
  21755. return;
  21756. }
  21757. this._forcePointsCloud = value;
  21758. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21759. },
  21760. enumerable: true,
  21761. configurable: true
  21762. });
  21763. Object.defineProperty(Scene.prototype, "onDispose", {
  21764. /** A function to be executed when this scene is disposed. */
  21765. set: function (callback) {
  21766. if (this._onDisposeObserver) {
  21767. this.onDisposeObservable.remove(this._onDisposeObserver);
  21768. }
  21769. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(Scene.prototype, "beforeRender", {
  21775. /** A function to be executed before rendering this scene */
  21776. set: function (callback) {
  21777. if (this._onBeforeRenderObserver) {
  21778. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21779. }
  21780. if (callback) {
  21781. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21782. }
  21783. },
  21784. enumerable: true,
  21785. configurable: true
  21786. });
  21787. Object.defineProperty(Scene.prototype, "afterRender", {
  21788. /** A function to be executed after rendering this scene */
  21789. set: function (callback) {
  21790. if (this._onAfterRenderObserver) {
  21791. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21792. }
  21793. if (callback) {
  21794. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21795. }
  21796. },
  21797. enumerable: true,
  21798. configurable: true
  21799. });
  21800. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21801. set: function (callback) {
  21802. if (this._onBeforeCameraRenderObserver) {
  21803. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21804. }
  21805. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21811. set: function (callback) {
  21812. if (this._onAfterCameraRenderObserver) {
  21813. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21814. }
  21815. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21816. },
  21817. enumerable: true,
  21818. configurable: true
  21819. });
  21820. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21821. get: function () {
  21822. if (!this._gamepadManager) {
  21823. this._gamepadManager = new BABYLON.GamepadManager(this);
  21824. }
  21825. return this._gamepadManager;
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21831. get: function () {
  21832. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21833. },
  21834. enumerable: true,
  21835. configurable: true
  21836. });
  21837. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21838. get: function () {
  21839. return this._useRightHandedSystem;
  21840. },
  21841. set: function (value) {
  21842. if (this._useRightHandedSystem === value) {
  21843. return;
  21844. }
  21845. this._useRightHandedSystem = value;
  21846. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21847. },
  21848. enumerable: true,
  21849. configurable: true
  21850. });
  21851. Scene.prototype.setStepId = function (newStepId) {
  21852. this._currentStepId = newStepId;
  21853. };
  21854. ;
  21855. Scene.prototype.getStepId = function () {
  21856. return this._currentStepId;
  21857. };
  21858. ;
  21859. Scene.prototype.getInternalStep = function () {
  21860. return this._currentInternalStep;
  21861. };
  21862. ;
  21863. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21864. get: function () {
  21865. return this._fogEnabled;
  21866. },
  21867. /**
  21868. * is fog enabled on this scene.
  21869. */
  21870. set: function (value) {
  21871. if (this._fogEnabled === value) {
  21872. return;
  21873. }
  21874. this._fogEnabled = value;
  21875. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21876. },
  21877. enumerable: true,
  21878. configurable: true
  21879. });
  21880. Object.defineProperty(Scene.prototype, "fogMode", {
  21881. get: function () {
  21882. return this._fogMode;
  21883. },
  21884. set: function (value) {
  21885. if (this._fogMode === value) {
  21886. return;
  21887. }
  21888. this._fogMode = value;
  21889. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21895. get: function () {
  21896. return this._shadowsEnabled;
  21897. },
  21898. set: function (value) {
  21899. if (this._shadowsEnabled === value) {
  21900. return;
  21901. }
  21902. this._shadowsEnabled = value;
  21903. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21909. get: function () {
  21910. return this._lightsEnabled;
  21911. },
  21912. set: function (value) {
  21913. if (this._lightsEnabled === value) {
  21914. return;
  21915. }
  21916. this._lightsEnabled = value;
  21917. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21918. },
  21919. enumerable: true,
  21920. configurable: true
  21921. });
  21922. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21923. /** The default material used on meshes when no material is affected */
  21924. get: function () {
  21925. if (!this._defaultMaterial) {
  21926. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21927. }
  21928. return this._defaultMaterial;
  21929. },
  21930. /** The default material used on meshes when no material is affected */
  21931. set: function (value) {
  21932. this._defaultMaterial = value;
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21938. get: function () {
  21939. return this._texturesEnabled;
  21940. },
  21941. set: function (value) {
  21942. if (this._texturesEnabled === value) {
  21943. return;
  21944. }
  21945. this._texturesEnabled = value;
  21946. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21952. get: function () {
  21953. return this._skeletonsEnabled;
  21954. },
  21955. set: function (value) {
  21956. if (this._skeletonsEnabled === value) {
  21957. return;
  21958. }
  21959. this._skeletonsEnabled = value;
  21960. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21961. },
  21962. enumerable: true,
  21963. configurable: true
  21964. });
  21965. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21966. get: function () {
  21967. if (!this._postProcessRenderPipelineManager) {
  21968. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21969. }
  21970. return this._postProcessRenderPipelineManager;
  21971. },
  21972. enumerable: true,
  21973. configurable: true
  21974. });
  21975. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21976. get: function () {
  21977. if (!this._mainSoundTrack) {
  21978. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21979. }
  21980. return this._mainSoundTrack;
  21981. },
  21982. enumerable: true,
  21983. configurable: true
  21984. });
  21985. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21986. get: function () {
  21987. return this._alternateRendering;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21993. get: function () {
  21994. return this._frustumPlanes;
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22000. /**
  22001. * Gets the current geometry buffer associated to the scene.
  22002. */
  22003. get: function () {
  22004. return this._geometryBufferRenderer;
  22005. },
  22006. /**
  22007. * Sets the current geometry buffer for the scene.
  22008. */
  22009. set: function (geometryBufferRenderer) {
  22010. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22011. this._geometryBufferRenderer = geometryBufferRenderer;
  22012. }
  22013. },
  22014. enumerable: true,
  22015. configurable: true
  22016. });
  22017. Object.defineProperty(Scene.prototype, "debugLayer", {
  22018. // Properties
  22019. get: function () {
  22020. if (!this._debugLayer) {
  22021. this._debugLayer = new BABYLON.DebugLayer(this);
  22022. }
  22023. return this._debugLayer;
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22029. get: function () {
  22030. return this._workerCollisions;
  22031. },
  22032. set: function (enabled) {
  22033. if (!BABYLON.CollisionCoordinatorLegacy) {
  22034. return;
  22035. }
  22036. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22037. this._workerCollisions = enabled;
  22038. if (this.collisionCoordinator) {
  22039. this.collisionCoordinator.destroy();
  22040. }
  22041. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22042. this.collisionCoordinator.init(this);
  22043. },
  22044. enumerable: true,
  22045. configurable: true
  22046. });
  22047. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22048. get: function () {
  22049. return this._selectionOctree;
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22055. /**
  22056. * The mesh that is currently under the pointer.
  22057. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22058. */
  22059. get: function () {
  22060. return this._pointerOverMesh;
  22061. },
  22062. enumerable: true,
  22063. configurable: true
  22064. });
  22065. Object.defineProperty(Scene.prototype, "pointerX", {
  22066. /**
  22067. * Current on-screen X position of the pointer
  22068. * @return {number} X position of the pointer
  22069. */
  22070. get: function () {
  22071. return this._pointerX;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Object.defineProperty(Scene.prototype, "pointerY", {
  22077. /**
  22078. * Current on-screen Y position of the pointer
  22079. * @return {number} Y position of the pointer
  22080. */
  22081. get: function () {
  22082. return this._pointerY;
  22083. },
  22084. enumerable: true,
  22085. configurable: true
  22086. });
  22087. Scene.prototype.getCachedMaterial = function () {
  22088. return this._cachedMaterial;
  22089. };
  22090. Scene.prototype.getCachedEffect = function () {
  22091. return this._cachedEffect;
  22092. };
  22093. Scene.prototype.getCachedVisibility = function () {
  22094. return this._cachedVisibility;
  22095. };
  22096. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22097. if (visibility === void 0) { visibility = 1; }
  22098. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22099. };
  22100. Scene.prototype.getBoundingBoxRenderer = function () {
  22101. if (!this._boundingBoxRenderer) {
  22102. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22103. }
  22104. return this._boundingBoxRenderer;
  22105. };
  22106. Scene.prototype.getOutlineRenderer = function () {
  22107. return this._outlineRenderer;
  22108. };
  22109. Scene.prototype.getEngine = function () {
  22110. return this._engine;
  22111. };
  22112. Scene.prototype.getTotalVertices = function () {
  22113. return this._totalVertices.current;
  22114. };
  22115. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22116. get: function () {
  22117. return this._totalVertices;
  22118. },
  22119. enumerable: true,
  22120. configurable: true
  22121. });
  22122. Scene.prototype.getActiveIndices = function () {
  22123. return this._activeIndices.current;
  22124. };
  22125. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22126. get: function () {
  22127. return this._activeIndices;
  22128. },
  22129. enumerable: true,
  22130. configurable: true
  22131. });
  22132. Scene.prototype.getActiveParticles = function () {
  22133. return this._activeParticles.current;
  22134. };
  22135. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22136. get: function () {
  22137. return this._activeParticles;
  22138. },
  22139. enumerable: true,
  22140. configurable: true
  22141. });
  22142. Scene.prototype.getActiveBones = function () {
  22143. return this._activeBones.current;
  22144. };
  22145. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22146. get: function () {
  22147. return this._activeBones;
  22148. },
  22149. enumerable: true,
  22150. configurable: true
  22151. });
  22152. // Stats
  22153. Scene.prototype.getInterFramePerfCounter = function () {
  22154. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22155. return 0;
  22156. };
  22157. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22158. get: function () {
  22159. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22160. return null;
  22161. },
  22162. enumerable: true,
  22163. configurable: true
  22164. });
  22165. Scene.prototype.getLastFrameDuration = function () {
  22166. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22167. return 0;
  22168. };
  22169. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22170. get: function () {
  22171. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22172. return null;
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22178. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22179. return 0;
  22180. };
  22181. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22182. get: function () {
  22183. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22184. return null;
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Scene.prototype.getActiveMeshes = function () {
  22190. return this._activeMeshes;
  22191. };
  22192. Scene.prototype.getRenderTargetsDuration = function () {
  22193. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22194. return 0;
  22195. };
  22196. Scene.prototype.getRenderDuration = function () {
  22197. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22198. return 0;
  22199. };
  22200. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22201. get: function () {
  22202. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22203. return null;
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Scene.prototype.getParticlesDuration = function () {
  22209. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22210. return 0;
  22211. };
  22212. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22213. get: function () {
  22214. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22215. return null;
  22216. },
  22217. enumerable: true,
  22218. configurable: true
  22219. });
  22220. Scene.prototype.getSpritesDuration = function () {
  22221. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22222. return 0;
  22223. };
  22224. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22225. get: function () {
  22226. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22227. return null;
  22228. },
  22229. enumerable: true,
  22230. configurable: true
  22231. });
  22232. Scene.prototype.getAnimationRatio = function () {
  22233. return this._animationRatio;
  22234. };
  22235. Scene.prototype.getRenderId = function () {
  22236. return this._renderId;
  22237. };
  22238. Scene.prototype.incrementRenderId = function () {
  22239. this._renderId++;
  22240. };
  22241. Scene.prototype._updatePointerPosition = function (evt) {
  22242. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22243. if (!canvasRect) {
  22244. return;
  22245. }
  22246. this._pointerX = evt.clientX - canvasRect.left;
  22247. this._pointerY = evt.clientY - canvasRect.top;
  22248. this._unTranslatedPointerX = this._pointerX;
  22249. this._unTranslatedPointerY = this._pointerY;
  22250. };
  22251. Scene.prototype._createUbo = function () {
  22252. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22253. this._sceneUbo.addUniform("viewProjection", 16);
  22254. this._sceneUbo.addUniform("view", 16);
  22255. };
  22256. Scene.prototype._createAlternateUbo = function () {
  22257. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22258. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22259. this._alternateSceneUbo.addUniform("view", 16);
  22260. };
  22261. // Pointers handling
  22262. /**
  22263. * Use this method to simulate a pointer move on a mesh
  22264. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22265. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22266. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22267. */
  22268. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22269. var evt = new PointerEvent("pointermove", pointerEventInit);
  22270. return this._processPointerMove(pickResult, evt);
  22271. };
  22272. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22273. var canvas = this._engine.getRenderingCanvas();
  22274. if (!canvas) {
  22275. return this;
  22276. }
  22277. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22278. this.setPointerOverSprite(null);
  22279. this.setPointerOverMesh(pickResult.pickedMesh);
  22280. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22281. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22282. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22283. }
  22284. else {
  22285. canvas.style.cursor = this.hoverCursor;
  22286. }
  22287. }
  22288. else {
  22289. canvas.style.cursor = this.defaultCursor;
  22290. }
  22291. }
  22292. else {
  22293. this.setPointerOverMesh(null);
  22294. // Sprites
  22295. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22296. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22297. this.setPointerOverSprite(pickResult.pickedSprite);
  22298. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22299. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22300. }
  22301. else {
  22302. canvas.style.cursor = this.hoverCursor;
  22303. }
  22304. }
  22305. else {
  22306. this.setPointerOverSprite(null);
  22307. // Restore pointer
  22308. canvas.style.cursor = this.defaultCursor;
  22309. }
  22310. }
  22311. if (pickResult) {
  22312. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22313. if (this.onPointerMove) {
  22314. this.onPointerMove(evt, pickResult, type);
  22315. }
  22316. if (this.onPointerObservable.hasObservers()) {
  22317. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22318. this.onPointerObservable.notifyObservers(pi, type);
  22319. }
  22320. }
  22321. return this;
  22322. };
  22323. /**
  22324. * Use this method to simulate a pointer down on a mesh
  22325. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22326. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22327. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22328. */
  22329. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22330. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22331. return this._processPointerDown(pickResult, evt);
  22332. };
  22333. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22334. var _this = this;
  22335. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22336. this._pickedDownMesh = pickResult.pickedMesh;
  22337. var actionManager = pickResult.pickedMesh.actionManager;
  22338. if (actionManager) {
  22339. if (actionManager.hasPickTriggers) {
  22340. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22341. switch (evt.button) {
  22342. case 0:
  22343. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22344. break;
  22345. case 1:
  22346. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22347. break;
  22348. case 2:
  22349. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22350. break;
  22351. }
  22352. }
  22353. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22354. window.setTimeout(function () {
  22355. 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);
  22356. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22357. if (_this._totalPointersPressed !== 0 &&
  22358. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22359. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22360. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22361. _this._startingPointerTime = 0;
  22362. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22363. }
  22364. }
  22365. }, Scene.LongPressDelay);
  22366. }
  22367. }
  22368. }
  22369. if (pickResult) {
  22370. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22371. if (this.onPointerDown) {
  22372. this.onPointerDown(evt, pickResult, type);
  22373. }
  22374. if (this.onPointerObservable.hasObservers()) {
  22375. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22376. this.onPointerObservable.notifyObservers(pi, type);
  22377. }
  22378. }
  22379. return this;
  22380. };
  22381. /**
  22382. * Use this method to simulate a pointer up on a mesh
  22383. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22384. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22385. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22386. */
  22387. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22388. var evt = new PointerEvent("pointerup", pointerEventInit);
  22389. var clickInfo = new ClickInfo();
  22390. clickInfo.singleClick = true;
  22391. clickInfo.ignore = true;
  22392. return this._processPointerUp(pickResult, evt, clickInfo);
  22393. };
  22394. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22395. if (pickResult && pickResult && pickResult.pickedMesh) {
  22396. this._pickedUpMesh = pickResult.pickedMesh;
  22397. if (this._pickedDownMesh === this._pickedUpMesh) {
  22398. if (this.onPointerPick) {
  22399. this.onPointerPick(evt, pickResult);
  22400. }
  22401. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22402. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22403. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22404. this.onPointerObservable.notifyObservers(pi, type_1);
  22405. }
  22406. }
  22407. if (pickResult.pickedMesh.actionManager) {
  22408. if (clickInfo.ignore) {
  22409. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22410. }
  22411. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22412. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22413. }
  22414. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22415. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22416. }
  22417. }
  22418. }
  22419. if (this._pickedDownMesh &&
  22420. this._pickedDownMesh.actionManager &&
  22421. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22422. this._pickedDownMesh !== this._pickedUpMesh) {
  22423. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22424. }
  22425. var type = BABYLON.PointerEventTypes.POINTERUP;
  22426. if (this.onPointerObservable.hasObservers()) {
  22427. if (!clickInfo.ignore) {
  22428. if (!clickInfo.hasSwiped) {
  22429. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22430. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22431. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22432. this.onPointerObservable.notifyObservers(pi, type_2);
  22433. }
  22434. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22435. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22436. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22437. this.onPointerObservable.notifyObservers(pi, type_3);
  22438. }
  22439. }
  22440. }
  22441. else {
  22442. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22443. this.onPointerObservable.notifyObservers(pi, type);
  22444. }
  22445. }
  22446. if (this.onPointerUp) {
  22447. this.onPointerUp(evt, pickResult, type);
  22448. }
  22449. return this;
  22450. };
  22451. /**
  22452. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22453. * @param attachUp defines if you want to attach events to pointerup
  22454. * @param attachDown defines if you want to attach events to pointerdown
  22455. * @param attachMove defines if you want to attach events to pointermove
  22456. */
  22457. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22458. var _this = this;
  22459. if (attachUp === void 0) { attachUp = true; }
  22460. if (attachDown === void 0) { attachDown = true; }
  22461. if (attachMove === void 0) { attachMove = true; }
  22462. this._initActionManager = function (act, clickInfo) {
  22463. if (!_this._meshPickProceed) {
  22464. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22465. _this._currentPickResult = pickResult;
  22466. if (pickResult) {
  22467. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22468. }
  22469. _this._meshPickProceed = true;
  22470. }
  22471. return act;
  22472. };
  22473. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22474. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22475. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22476. btn !== _this._previousButtonPressed) {
  22477. _this._doubleClickOccured = false;
  22478. clickInfo.singleClick = true;
  22479. clickInfo.ignore = false;
  22480. cb(clickInfo, _this._currentPickResult);
  22481. }
  22482. };
  22483. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22484. var clickInfo = new ClickInfo();
  22485. _this._currentPickResult = null;
  22486. var act = null;
  22487. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22488. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22489. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22490. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22491. act = _this._initActionManager(act, clickInfo);
  22492. if (act)
  22493. checkPicking = act.hasPickTriggers;
  22494. }
  22495. if (checkPicking) {
  22496. var btn = evt.button;
  22497. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22498. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22499. if (!clickInfo.hasSwiped) {
  22500. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22501. if (!checkSingleClickImmediately) {
  22502. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22503. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22504. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22505. act = _this._initActionManager(act, clickInfo);
  22506. if (act)
  22507. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22508. }
  22509. }
  22510. if (checkSingleClickImmediately) {
  22511. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22512. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22513. btn !== _this._previousButtonPressed) {
  22514. clickInfo.singleClick = true;
  22515. cb(clickInfo, _this._currentPickResult);
  22516. }
  22517. }
  22518. else {
  22519. // wait that no double click has been raised during the double click delay
  22520. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22521. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22522. }
  22523. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22524. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22525. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22526. act = _this._initActionManager(act, clickInfo);
  22527. if (act)
  22528. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22529. }
  22530. if (checkDoubleClick) {
  22531. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22532. if (btn === _this._previousButtonPressed &&
  22533. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22534. !_this._doubleClickOccured) {
  22535. // pointer has not moved for 2 clicks, it's a double click
  22536. if (!clickInfo.hasSwiped &&
  22537. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22538. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22539. _this._previousStartingPointerTime = 0;
  22540. _this._doubleClickOccured = true;
  22541. clickInfo.doubleClick = true;
  22542. clickInfo.ignore = false;
  22543. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22544. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22545. }
  22546. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22547. cb(clickInfo, _this._currentPickResult);
  22548. }
  22549. else {
  22550. _this._doubleClickOccured = false;
  22551. _this._previousStartingPointerTime = _this._startingPointerTime;
  22552. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22553. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22554. _this._previousButtonPressed = btn;
  22555. if (Scene.ExclusiveDoubleClickMode) {
  22556. if (_this._previousDelayedSimpleClickTimeout) {
  22557. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22558. }
  22559. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22560. cb(clickInfo, _this._previousPickResult);
  22561. }
  22562. else {
  22563. cb(clickInfo, _this._currentPickResult);
  22564. }
  22565. }
  22566. }
  22567. else {
  22568. _this._doubleClickOccured = false;
  22569. _this._previousStartingPointerTime = _this._startingPointerTime;
  22570. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22571. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22572. _this._previousButtonPressed = btn;
  22573. }
  22574. }
  22575. }
  22576. }
  22577. clickInfo.ignore = true;
  22578. cb(clickInfo, _this._currentPickResult);
  22579. };
  22580. this._spritePredicate = function (sprite) {
  22581. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22582. };
  22583. this._onPointerMove = function (evt) {
  22584. _this._updatePointerPosition(evt);
  22585. // PreObservable support
  22586. if (_this.onPrePointerObservable.hasObservers()) {
  22587. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22588. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22589. _this.onPrePointerObservable.notifyObservers(pi, type);
  22590. if (pi.skipOnPointerObservable) {
  22591. return;
  22592. }
  22593. }
  22594. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22595. return;
  22596. }
  22597. if (!_this.pointerMovePredicate) {
  22598. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22599. }
  22600. // Meshes
  22601. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22602. _this._processPointerMove(pickResult, evt);
  22603. };
  22604. this._onPointerDown = function (evt) {
  22605. _this._totalPointersPressed++;
  22606. _this._pickedDownMesh = null;
  22607. _this._meshPickProceed = false;
  22608. _this._updatePointerPosition(evt);
  22609. if (_this.preventDefaultOnPointerDown && canvas) {
  22610. evt.preventDefault();
  22611. canvas.focus();
  22612. }
  22613. // PreObservable support
  22614. if (_this.onPrePointerObservable.hasObservers()) {
  22615. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22616. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22617. _this.onPrePointerObservable.notifyObservers(pi, type);
  22618. if (pi.skipOnPointerObservable) {
  22619. return;
  22620. }
  22621. }
  22622. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22623. return;
  22624. }
  22625. _this._startingPointerPosition.x = _this._pointerX;
  22626. _this._startingPointerPosition.y = _this._pointerY;
  22627. _this._startingPointerTime = new Date().getTime();
  22628. if (!_this.pointerDownPredicate) {
  22629. _this.pointerDownPredicate = function (mesh) {
  22630. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22631. };
  22632. }
  22633. // Meshes
  22634. _this._pickedDownMesh = null;
  22635. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22636. _this._processPointerDown(pickResult, evt);
  22637. // Sprites
  22638. _this._pickedDownSprite = null;
  22639. if (_this.spriteManagers.length > 0) {
  22640. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22641. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22642. if (pickResult.pickedSprite.actionManager) {
  22643. _this._pickedDownSprite = pickResult.pickedSprite;
  22644. switch (evt.button) {
  22645. case 0:
  22646. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22647. break;
  22648. case 1:
  22649. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22650. break;
  22651. case 2:
  22652. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22653. break;
  22654. }
  22655. if (pickResult.pickedSprite.actionManager) {
  22656. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22657. }
  22658. }
  22659. }
  22660. }
  22661. };
  22662. this._onPointerUp = function (evt) {
  22663. if (_this._totalPointersPressed === 0) {
  22664. return; // So we need to test it the pointer down was pressed before.
  22665. }
  22666. _this._totalPointersPressed--;
  22667. _this._pickedUpMesh = null;
  22668. _this._meshPickProceed = false;
  22669. _this._updatePointerPosition(evt);
  22670. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22671. // PreObservable support
  22672. if (_this.onPrePointerObservable.hasObservers()) {
  22673. if (!clickInfo.ignore) {
  22674. if (!clickInfo.hasSwiped) {
  22675. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22676. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22677. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22678. _this.onPrePointerObservable.notifyObservers(pi, type);
  22679. if (pi.skipOnPointerObservable) {
  22680. return;
  22681. }
  22682. }
  22683. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22684. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22685. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22686. _this.onPrePointerObservable.notifyObservers(pi, type);
  22687. if (pi.skipOnPointerObservable) {
  22688. return;
  22689. }
  22690. }
  22691. }
  22692. }
  22693. else {
  22694. var type = BABYLON.PointerEventTypes.POINTERUP;
  22695. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22696. _this.onPrePointerObservable.notifyObservers(pi, type);
  22697. if (pi.skipOnPointerObservable) {
  22698. return;
  22699. }
  22700. }
  22701. }
  22702. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22703. return;
  22704. }
  22705. if (!_this.pointerUpPredicate) {
  22706. _this.pointerUpPredicate = function (mesh) {
  22707. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22708. };
  22709. }
  22710. // Meshes
  22711. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22712. _this._initActionManager(null, clickInfo);
  22713. }
  22714. if (!pickResult) {
  22715. pickResult = _this._currentPickResult;
  22716. }
  22717. _this._processPointerUp(pickResult, evt, clickInfo);
  22718. // Sprites
  22719. if (_this.spriteManagers.length > 0) {
  22720. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22721. if (spritePickResult) {
  22722. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22723. if (spritePickResult.pickedSprite.actionManager) {
  22724. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22725. if (spritePickResult.pickedSprite.actionManager) {
  22726. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22727. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22728. }
  22729. }
  22730. }
  22731. }
  22732. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22733. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22734. }
  22735. }
  22736. }
  22737. _this._previousPickResult = _this._currentPickResult;
  22738. });
  22739. };
  22740. this._onKeyDown = function (evt) {
  22741. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22742. if (_this.onPreKeyboardObservable.hasObservers()) {
  22743. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22744. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22745. if (pi.skipOnPointerObservable) {
  22746. return;
  22747. }
  22748. }
  22749. if (_this.onKeyboardObservable.hasObservers()) {
  22750. var pi = new BABYLON.KeyboardInfo(type, evt);
  22751. _this.onKeyboardObservable.notifyObservers(pi, type);
  22752. }
  22753. if (_this.actionManager) {
  22754. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22755. }
  22756. };
  22757. this._onKeyUp = function (evt) {
  22758. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22759. if (_this.onPreKeyboardObservable.hasObservers()) {
  22760. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22761. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22762. if (pi.skipOnPointerObservable) {
  22763. return;
  22764. }
  22765. }
  22766. if (_this.onKeyboardObservable.hasObservers()) {
  22767. var pi = new BABYLON.KeyboardInfo(type, evt);
  22768. _this.onKeyboardObservable.notifyObservers(pi, type);
  22769. }
  22770. if (_this.actionManager) {
  22771. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22772. }
  22773. };
  22774. var engine = this.getEngine();
  22775. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22776. if (!canvas) {
  22777. return;
  22778. }
  22779. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22780. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22781. });
  22782. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22783. if (!canvas) {
  22784. return;
  22785. }
  22786. canvas.removeEventListener("keydown", _this._onKeyDown);
  22787. canvas.removeEventListener("keyup", _this._onKeyUp);
  22788. });
  22789. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22790. var canvas = this._engine.getRenderingCanvas();
  22791. if (!canvas) {
  22792. return;
  22793. }
  22794. if (attachMove) {
  22795. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22796. // Wheel
  22797. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22798. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22799. }
  22800. if (attachDown) {
  22801. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22802. }
  22803. if (attachUp) {
  22804. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22805. }
  22806. canvas.tabIndex = 1;
  22807. };
  22808. Scene.prototype.detachControl = function () {
  22809. var engine = this.getEngine();
  22810. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22811. var canvas = engine.getRenderingCanvas();
  22812. if (!canvas) {
  22813. return;
  22814. }
  22815. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22816. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22817. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22818. if (this._onCanvasBlurObserver) {
  22819. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22820. }
  22821. if (this._onCanvasFocusObserver) {
  22822. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22823. }
  22824. // Wheel
  22825. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22826. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22827. // Keyboard
  22828. canvas.removeEventListener("keydown", this._onKeyDown);
  22829. canvas.removeEventListener("keyup", this._onKeyUp);
  22830. // Observables
  22831. this.onKeyboardObservable.clear();
  22832. this.onPreKeyboardObservable.clear();
  22833. this.onPointerObservable.clear();
  22834. this.onPrePointerObservable.clear();
  22835. };
  22836. /**
  22837. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22838. * Delay loaded resources are not taking in account
  22839. * @return true if all required resources are ready
  22840. */
  22841. Scene.prototype.isReady = function () {
  22842. if (this._isDisposed) {
  22843. return false;
  22844. }
  22845. if (this._pendingData.length > 0) {
  22846. return false;
  22847. }
  22848. var index;
  22849. var engine = this.getEngine();
  22850. // Geometries
  22851. for (index = 0; index < this._geometries.length; index++) {
  22852. var geometry = this._geometries[index];
  22853. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22854. return false;
  22855. }
  22856. }
  22857. // Meshes
  22858. for (index = 0; index < this.meshes.length; index++) {
  22859. var mesh = this.meshes[index];
  22860. if (!mesh.isEnabled()) {
  22861. continue;
  22862. }
  22863. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22864. continue;
  22865. }
  22866. if (!mesh.isReady(true)) {
  22867. return false;
  22868. }
  22869. // Effect layers
  22870. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22871. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22872. var layer = _a[_i];
  22873. if (!layer.hasMesh(mesh)) {
  22874. continue;
  22875. }
  22876. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22877. var subMesh = _c[_b];
  22878. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22879. return false;
  22880. }
  22881. }
  22882. }
  22883. }
  22884. // Particles
  22885. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  22886. var particleSystem = _e[_d];
  22887. if (!particleSystem.isReady()) {
  22888. return false;
  22889. }
  22890. }
  22891. return true;
  22892. };
  22893. Scene.prototype.resetCachedMaterial = function () {
  22894. this._cachedMaterial = null;
  22895. this._cachedEffect = null;
  22896. this._cachedVisibility = null;
  22897. };
  22898. Scene.prototype.registerBeforeRender = function (func) {
  22899. this.onBeforeRenderObservable.add(func);
  22900. };
  22901. Scene.prototype.unregisterBeforeRender = function (func) {
  22902. this.onBeforeRenderObservable.removeCallback(func);
  22903. };
  22904. Scene.prototype.registerAfterRender = function (func) {
  22905. this.onAfterRenderObservable.add(func);
  22906. };
  22907. Scene.prototype.unregisterAfterRender = function (func) {
  22908. this.onAfterRenderObservable.removeCallback(func);
  22909. };
  22910. Scene.prototype._executeOnceBeforeRender = function (func) {
  22911. var _this = this;
  22912. var execFunc = function () {
  22913. func();
  22914. setTimeout(function () {
  22915. _this.unregisterBeforeRender(execFunc);
  22916. });
  22917. };
  22918. this.registerBeforeRender(execFunc);
  22919. };
  22920. /**
  22921. * The provided function will run before render once and will be disposed afterwards.
  22922. * A timeout delay can be provided so that the function will be executed in N ms.
  22923. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22924. * @param func The function to be executed.
  22925. * @param timeout optional delay in ms
  22926. */
  22927. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22928. var _this = this;
  22929. if (timeout !== undefined) {
  22930. setTimeout(function () {
  22931. _this._executeOnceBeforeRender(func);
  22932. }, timeout);
  22933. }
  22934. else {
  22935. this._executeOnceBeforeRender(func);
  22936. }
  22937. };
  22938. Scene.prototype._addPendingData = function (data) {
  22939. this._pendingData.push(data);
  22940. };
  22941. Scene.prototype._removePendingData = function (data) {
  22942. var wasLoading = this.isLoading;
  22943. var index = this._pendingData.indexOf(data);
  22944. if (index !== -1) {
  22945. this._pendingData.splice(index, 1);
  22946. }
  22947. if (wasLoading && !this.isLoading) {
  22948. this.onDataLoadedObservable.notifyObservers(this);
  22949. }
  22950. };
  22951. Scene.prototype.getWaitingItemsCount = function () {
  22952. return this._pendingData.length;
  22953. };
  22954. Object.defineProperty(Scene.prototype, "isLoading", {
  22955. get: function () {
  22956. return this._pendingData.length > 0;
  22957. },
  22958. enumerable: true,
  22959. configurable: true
  22960. });
  22961. /**
  22962. * Registers a function to be executed when the scene is ready.
  22963. * @param {Function} func - the function to be executed.
  22964. */
  22965. Scene.prototype.executeWhenReady = function (func) {
  22966. var _this = this;
  22967. this.onReadyObservable.add(func);
  22968. if (this._executeWhenReadyTimeoutId !== -1) {
  22969. return;
  22970. }
  22971. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22972. _this._checkIsReady();
  22973. }, 150);
  22974. };
  22975. /**
  22976. * Returns a promise that resolves when the scene is ready.
  22977. * @returns A promise that resolves when the scene is ready.
  22978. */
  22979. Scene.prototype.whenReadyAsync = function () {
  22980. var _this = this;
  22981. return new Promise(function (resolve) {
  22982. _this.executeWhenReady(function () {
  22983. resolve();
  22984. });
  22985. });
  22986. };
  22987. Scene.prototype._checkIsReady = function () {
  22988. var _this = this;
  22989. if (this.isReady()) {
  22990. this.onReadyObservable.notifyObservers(this);
  22991. this.onReadyObservable.clear();
  22992. this._executeWhenReadyTimeoutId = -1;
  22993. return;
  22994. }
  22995. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22996. _this._checkIsReady();
  22997. }, 150);
  22998. };
  22999. // Animations
  23000. /**
  23001. * Will start the animation sequence of a given target
  23002. * @param target - the target
  23003. * @param {number} from - from which frame should animation start
  23004. * @param {number} to - till which frame should animation run.
  23005. * @param {boolean} [loop] - should the animation loop
  23006. * @param {number} [speedRatio] - the speed in which to run the animation
  23007. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23008. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23009. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23010. * See BABYLON.Animatable
  23011. */
  23012. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23013. if (speedRatio === void 0) { speedRatio = 1.0; }
  23014. if (from > to && speedRatio > 0) {
  23015. speedRatio *= -1;
  23016. }
  23017. this.stopAnimation(target);
  23018. if (!animatable) {
  23019. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23020. }
  23021. // Local animations
  23022. if (target.animations) {
  23023. animatable.appendAnimations(target, target.animations);
  23024. }
  23025. // Children animations
  23026. if (target.getAnimatables) {
  23027. var animatables = target.getAnimatables();
  23028. for (var index = 0; index < animatables.length; index++) {
  23029. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23030. }
  23031. }
  23032. animatable.reset();
  23033. return animatable;
  23034. };
  23035. /**
  23036. * Begin a new animation on a given node
  23037. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23038. * @param {BABYLON.Animation[]} defines the list of animations to start
  23039. * @param {number} from defines the initial value
  23040. * @param {number} to defines the final value
  23041. * @param {boolean} loop defines if you want animation to loop (off by default)
  23042. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23043. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23044. * @returns the list of created animatables
  23045. */
  23046. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23047. if (speedRatio === undefined) {
  23048. speedRatio = 1.0;
  23049. }
  23050. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23051. return animatable;
  23052. };
  23053. /**
  23054. * Begin a new animation on a given node and its hierarchy
  23055. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23056. * @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.
  23057. * @param {BABYLON.Animation[]} defines the list of animations to start
  23058. * @param {number} from defines the initial value
  23059. * @param {number} to defines the final value
  23060. * @param {boolean} loop defines if you want animation to loop (off by default)
  23061. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23062. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23063. * @returns the list of animatables created for all nodes
  23064. */
  23065. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23066. var children = target.getDescendants(directDescendantsOnly);
  23067. var result = [];
  23068. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23069. var child = children_1[_i];
  23070. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23071. }
  23072. return result;
  23073. };
  23074. Scene.prototype.getAnimatableByTarget = function (target) {
  23075. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23076. if (this._activeAnimatables[index].target === target) {
  23077. return this._activeAnimatables[index];
  23078. }
  23079. }
  23080. return null;
  23081. };
  23082. Object.defineProperty(Scene.prototype, "animatables", {
  23083. get: function () {
  23084. return this._activeAnimatables;
  23085. },
  23086. enumerable: true,
  23087. configurable: true
  23088. });
  23089. /**
  23090. * Will stop the animation of the given target
  23091. * @param target - the target
  23092. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23093. * @see beginAnimation
  23094. */
  23095. Scene.prototype.stopAnimation = function (target, animationName) {
  23096. var animatable = this.getAnimatableByTarget(target);
  23097. if (animatable) {
  23098. animatable.stop(animationName);
  23099. }
  23100. };
  23101. /**
  23102. * Stops and removes all animations that have been applied to the scene
  23103. */
  23104. Scene.prototype.stopAllAnimations = function () {
  23105. if (this._activeAnimatables) {
  23106. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23107. this._activeAnimatables[i].stop();
  23108. }
  23109. this._activeAnimatables = [];
  23110. }
  23111. };
  23112. Scene.prototype._animate = function () {
  23113. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23114. return;
  23115. }
  23116. // Getting time
  23117. var now = BABYLON.Tools.Now;
  23118. if (!this._animationTimeLast) {
  23119. if (this._pendingData.length > 0) {
  23120. return;
  23121. }
  23122. this._animationTimeLast = now;
  23123. }
  23124. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23125. this._animationTime += deltaTime;
  23126. this._animationTimeLast = now;
  23127. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23128. this._activeAnimatables[index]._animate(this._animationTime);
  23129. }
  23130. };
  23131. // Matrix
  23132. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23133. this._useAlternateCameraConfiguration = active;
  23134. };
  23135. Scene.prototype.getViewMatrix = function () {
  23136. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23137. };
  23138. Scene.prototype.getProjectionMatrix = function () {
  23139. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23140. };
  23141. Scene.prototype.getTransformMatrix = function () {
  23142. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23143. };
  23144. Scene.prototype.setTransformMatrix = function (view, projection) {
  23145. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23146. return;
  23147. }
  23148. this._viewUpdateFlag = view.updateFlag;
  23149. this._projectionUpdateFlag = projection.updateFlag;
  23150. this._viewMatrix = view;
  23151. this._projectionMatrix = projection;
  23152. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23153. // Update frustum
  23154. if (!this._frustumPlanes) {
  23155. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23156. }
  23157. else {
  23158. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23159. }
  23160. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23161. var otherCamera = this.activeCamera._alternateCamera;
  23162. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23163. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23164. }
  23165. if (this._sceneUbo.useUbo) {
  23166. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23167. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23168. this._sceneUbo.update();
  23169. }
  23170. };
  23171. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23172. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23173. return;
  23174. }
  23175. this._alternateViewUpdateFlag = view.updateFlag;
  23176. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23177. this._alternateViewMatrix = view;
  23178. this._alternateProjectionMatrix = projection;
  23179. if (!this._alternateTransformMatrix) {
  23180. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23181. }
  23182. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23183. if (!this._alternateSceneUbo) {
  23184. this._createAlternateUbo();
  23185. }
  23186. if (this._alternateSceneUbo.useUbo) {
  23187. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23188. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23189. this._alternateSceneUbo.update();
  23190. }
  23191. };
  23192. Scene.prototype.getSceneUniformBuffer = function () {
  23193. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23194. };
  23195. // Methods
  23196. Scene.prototype.getUniqueId = function () {
  23197. var result = Scene._uniqueIdCounter;
  23198. Scene._uniqueIdCounter++;
  23199. return result;
  23200. };
  23201. Scene.prototype.addMesh = function (newMesh) {
  23202. this.meshes.push(newMesh);
  23203. //notify the collision coordinator
  23204. if (this.collisionCoordinator) {
  23205. this.collisionCoordinator.onMeshAdded(newMesh);
  23206. }
  23207. newMesh._resyncLightSources();
  23208. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23209. };
  23210. Scene.prototype.removeMesh = function (toRemove) {
  23211. var index = this.meshes.indexOf(toRemove);
  23212. if (index !== -1) {
  23213. // Remove from the scene if mesh found
  23214. this.meshes.splice(index, 1);
  23215. }
  23216. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23217. return index;
  23218. };
  23219. Scene.prototype.addTransformNode = function (newTransformNode) {
  23220. this.transformNodes.push(newTransformNode);
  23221. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23222. };
  23223. Scene.prototype.removeTransformNode = function (toRemove) {
  23224. var index = this.transformNodes.indexOf(toRemove);
  23225. if (index !== -1) {
  23226. // Remove from the scene if found
  23227. this.transformNodes.splice(index, 1);
  23228. }
  23229. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23230. return index;
  23231. };
  23232. Scene.prototype.removeSkeleton = function (toRemove) {
  23233. var index = this.skeletons.indexOf(toRemove);
  23234. if (index !== -1) {
  23235. // Remove from the scene if found
  23236. this.skeletons.splice(index, 1);
  23237. }
  23238. return index;
  23239. };
  23240. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23241. var index = this.morphTargetManagers.indexOf(toRemove);
  23242. if (index !== -1) {
  23243. // Remove from the scene if found
  23244. this.morphTargetManagers.splice(index, 1);
  23245. }
  23246. return index;
  23247. };
  23248. Scene.prototype.removeLight = function (toRemove) {
  23249. var index = this.lights.indexOf(toRemove);
  23250. if (index !== -1) {
  23251. // Remove from meshes
  23252. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23253. var mesh = _a[_i];
  23254. mesh._removeLightSource(toRemove);
  23255. }
  23256. // Remove from the scene if mesh found
  23257. this.lights.splice(index, 1);
  23258. this.sortLightsByPriority();
  23259. }
  23260. this.onLightRemovedObservable.notifyObservers(toRemove);
  23261. return index;
  23262. };
  23263. Scene.prototype.removeCamera = function (toRemove) {
  23264. var index = this.cameras.indexOf(toRemove);
  23265. if (index !== -1) {
  23266. // Remove from the scene if mesh found
  23267. this.cameras.splice(index, 1);
  23268. }
  23269. // Remove from activeCameras
  23270. var index2 = this.activeCameras.indexOf(toRemove);
  23271. if (index2 !== -1) {
  23272. // Remove from the scene if mesh found
  23273. this.activeCameras.splice(index2, 1);
  23274. }
  23275. // Reset the activeCamera
  23276. if (this.activeCamera === toRemove) {
  23277. if (this.cameras.length > 0) {
  23278. this.activeCamera = this.cameras[0];
  23279. }
  23280. else {
  23281. this.activeCamera = null;
  23282. }
  23283. }
  23284. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23285. return index;
  23286. };
  23287. Scene.prototype.removeParticleSystem = function (toRemove) {
  23288. var index = this.particleSystems.indexOf(toRemove);
  23289. if (index !== -1) {
  23290. this.particleSystems.splice(index, 1);
  23291. }
  23292. return index;
  23293. };
  23294. ;
  23295. Scene.prototype.removeAnimation = function (toRemove) {
  23296. var index = this.animations.indexOf(toRemove);
  23297. if (index !== -1) {
  23298. this.animations.splice(index, 1);
  23299. }
  23300. return index;
  23301. };
  23302. ;
  23303. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23304. var index = this.multiMaterials.indexOf(toRemove);
  23305. if (index !== -1) {
  23306. this.multiMaterials.splice(index, 1);
  23307. }
  23308. return index;
  23309. };
  23310. ;
  23311. Scene.prototype.removeMaterial = function (toRemove) {
  23312. var index = this.materials.indexOf(toRemove);
  23313. if (index !== -1) {
  23314. this.materials.splice(index, 1);
  23315. }
  23316. return index;
  23317. };
  23318. ;
  23319. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23320. var index = this.lensFlareSystems.indexOf(toRemove);
  23321. if (index !== -1) {
  23322. this.lensFlareSystems.splice(index, 1);
  23323. }
  23324. return index;
  23325. };
  23326. ;
  23327. Scene.prototype.removeActionManager = function (toRemove) {
  23328. var index = this._actionManagers.indexOf(toRemove);
  23329. if (index !== -1) {
  23330. this._actionManagers.splice(index, 1);
  23331. }
  23332. return index;
  23333. };
  23334. ;
  23335. Scene.prototype.addLight = function (newLight) {
  23336. this.lights.push(newLight);
  23337. this.sortLightsByPriority();
  23338. // Add light to all meshes (To support if the light is removed and then readded)
  23339. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23340. var mesh = _a[_i];
  23341. if (mesh._lightSources.indexOf(newLight) === -1) {
  23342. mesh._lightSources.push(newLight);
  23343. mesh._resyncLightSources();
  23344. }
  23345. }
  23346. this.onNewLightAddedObservable.notifyObservers(newLight);
  23347. };
  23348. Scene.prototype.sortLightsByPriority = function () {
  23349. if (this.requireLightSorting) {
  23350. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23351. }
  23352. };
  23353. Scene.prototype.addCamera = function (newCamera) {
  23354. this.cameras.push(newCamera);
  23355. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23356. };
  23357. Scene.prototype.addSkeleton = function (newSkeleton) {
  23358. this.skeletons.push(newSkeleton);
  23359. };
  23360. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23361. this.particleSystems.push(newParticleSystem);
  23362. };
  23363. Scene.prototype.addAnimation = function (newAnimation) {
  23364. this.animations.push(newAnimation);
  23365. };
  23366. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23367. this.multiMaterials.push(newMultiMaterial);
  23368. };
  23369. Scene.prototype.addMaterial = function (newMaterial) {
  23370. this.materials.push(newMaterial);
  23371. };
  23372. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23373. this.morphTargetManagers.push(newMorphTargetManager);
  23374. };
  23375. Scene.prototype.addGeometry = function (newGeometrie) {
  23376. this._geometries.push(newGeometrie);
  23377. };
  23378. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23379. this.lensFlareSystems.push(newLensFlareSystem);
  23380. };
  23381. Scene.prototype.addActionManager = function (newActionManager) {
  23382. this._actionManagers.push(newActionManager);
  23383. };
  23384. /**
  23385. * Switch active camera
  23386. * @param {Camera} newCamera - new active camera
  23387. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23388. */
  23389. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23390. if (attachControl === void 0) { attachControl = true; }
  23391. var canvas = this._engine.getRenderingCanvas();
  23392. if (!canvas) {
  23393. return;
  23394. }
  23395. if (this.activeCamera) {
  23396. this.activeCamera.detachControl(canvas);
  23397. }
  23398. this.activeCamera = newCamera;
  23399. if (attachControl) {
  23400. newCamera.attachControl(canvas);
  23401. }
  23402. };
  23403. /**
  23404. * sets the active camera of the scene using its ID
  23405. * @param {string} id - the camera's ID
  23406. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23407. * @see activeCamera
  23408. */
  23409. Scene.prototype.setActiveCameraByID = function (id) {
  23410. var camera = this.getCameraByID(id);
  23411. if (camera) {
  23412. this.activeCamera = camera;
  23413. return camera;
  23414. }
  23415. return null;
  23416. };
  23417. /**
  23418. * sets the active camera of the scene using its name
  23419. * @param {string} name - the camera's name
  23420. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23421. * @see activeCamera
  23422. */
  23423. Scene.prototype.setActiveCameraByName = function (name) {
  23424. var camera = this.getCameraByName(name);
  23425. if (camera) {
  23426. this.activeCamera = camera;
  23427. return camera;
  23428. }
  23429. return null;
  23430. };
  23431. /**
  23432. * get an animation group using its name
  23433. * @param {string} the material's name
  23434. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23435. */
  23436. Scene.prototype.getAnimationGroupByName = function (name) {
  23437. for (var index = 0; index < this.animationGroups.length; index++) {
  23438. if (this.animationGroups[index].name === name) {
  23439. return this.animationGroups[index];
  23440. }
  23441. }
  23442. return null;
  23443. };
  23444. /**
  23445. * get a material using its id
  23446. * @param {string} the material's ID
  23447. * @return {BABYLON.Material|null} the material or null if none found.
  23448. */
  23449. Scene.prototype.getMaterialByID = function (id) {
  23450. for (var index = 0; index < this.materials.length; index++) {
  23451. if (this.materials[index].id === id) {
  23452. return this.materials[index];
  23453. }
  23454. }
  23455. return null;
  23456. };
  23457. /**
  23458. * get a material using its name
  23459. * @param {string} the material's name
  23460. * @return {BABYLON.Material|null} the material or null if none found.
  23461. */
  23462. Scene.prototype.getMaterialByName = function (name) {
  23463. for (var index = 0; index < this.materials.length; index++) {
  23464. if (this.materials[index].name === name) {
  23465. return this.materials[index];
  23466. }
  23467. }
  23468. return null;
  23469. };
  23470. Scene.prototype.getLensFlareSystemByName = function (name) {
  23471. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23472. if (this.lensFlareSystems[index].name === name) {
  23473. return this.lensFlareSystems[index];
  23474. }
  23475. }
  23476. return null;
  23477. };
  23478. Scene.prototype.getLensFlareSystemByID = function (id) {
  23479. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23480. if (this.lensFlareSystems[index].id === id) {
  23481. return this.lensFlareSystems[index];
  23482. }
  23483. }
  23484. return null;
  23485. };
  23486. Scene.prototype.getCameraByID = function (id) {
  23487. for (var index = 0; index < this.cameras.length; index++) {
  23488. if (this.cameras[index].id === id) {
  23489. return this.cameras[index];
  23490. }
  23491. }
  23492. return null;
  23493. };
  23494. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23495. for (var index = 0; index < this.cameras.length; index++) {
  23496. if (this.cameras[index].uniqueId === uniqueId) {
  23497. return this.cameras[index];
  23498. }
  23499. }
  23500. return null;
  23501. };
  23502. /**
  23503. * get a camera using its name
  23504. * @param {string} the camera's name
  23505. * @return {BABYLON.Camera|null} the camera or null if none found.
  23506. */
  23507. Scene.prototype.getCameraByName = function (name) {
  23508. for (var index = 0; index < this.cameras.length; index++) {
  23509. if (this.cameras[index].name === name) {
  23510. return this.cameras[index];
  23511. }
  23512. }
  23513. return null;
  23514. };
  23515. /**
  23516. * get a bone using its id
  23517. * @param {string} the bone's id
  23518. * @return {BABYLON.Bone|null} the bone or null if not found
  23519. */
  23520. Scene.prototype.getBoneByID = function (id) {
  23521. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23522. var skeleton = this.skeletons[skeletonIndex];
  23523. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23524. if (skeleton.bones[boneIndex].id === id) {
  23525. return skeleton.bones[boneIndex];
  23526. }
  23527. }
  23528. }
  23529. return null;
  23530. };
  23531. /**
  23532. * get a bone using its id
  23533. * @param {string} the bone's name
  23534. * @return {BABYLON.Bone|null} the bone or null if not found
  23535. */
  23536. Scene.prototype.getBoneByName = function (name) {
  23537. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23538. var skeleton = this.skeletons[skeletonIndex];
  23539. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23540. if (skeleton.bones[boneIndex].name === name) {
  23541. return skeleton.bones[boneIndex];
  23542. }
  23543. }
  23544. }
  23545. return null;
  23546. };
  23547. /**
  23548. * get a light node using its name
  23549. * @param {string} the light's name
  23550. * @return {BABYLON.Light|null} the light or null if none found.
  23551. */
  23552. Scene.prototype.getLightByName = function (name) {
  23553. for (var index = 0; index < this.lights.length; index++) {
  23554. if (this.lights[index].name === name) {
  23555. return this.lights[index];
  23556. }
  23557. }
  23558. return null;
  23559. };
  23560. /**
  23561. * get a light node using its ID
  23562. * @param {string} the light's id
  23563. * @return {BABYLON.Light|null} the light or null if none found.
  23564. */
  23565. Scene.prototype.getLightByID = function (id) {
  23566. for (var index = 0; index < this.lights.length; index++) {
  23567. if (this.lights[index].id === id) {
  23568. return this.lights[index];
  23569. }
  23570. }
  23571. return null;
  23572. };
  23573. /**
  23574. * get a light node using its scene-generated unique ID
  23575. * @param {number} the light's unique id
  23576. * @return {BABYLON.Light|null} the light or null if none found.
  23577. */
  23578. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23579. for (var index = 0; index < this.lights.length; index++) {
  23580. if (this.lights[index].uniqueId === uniqueId) {
  23581. return this.lights[index];
  23582. }
  23583. }
  23584. return null;
  23585. };
  23586. /**
  23587. * get a particle system by id
  23588. * @param id {number} the particle system id
  23589. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23590. */
  23591. Scene.prototype.getParticleSystemByID = function (id) {
  23592. for (var index = 0; index < this.particleSystems.length; index++) {
  23593. if (this.particleSystems[index].id === id) {
  23594. return this.particleSystems[index];
  23595. }
  23596. }
  23597. return null;
  23598. };
  23599. /**
  23600. * get a geometry using its ID
  23601. * @param {string} the geometry's id
  23602. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23603. */
  23604. Scene.prototype.getGeometryByID = function (id) {
  23605. for (var index = 0; index < this._geometries.length; index++) {
  23606. if (this._geometries[index].id === id) {
  23607. return this._geometries[index];
  23608. }
  23609. }
  23610. return null;
  23611. };
  23612. /**
  23613. * add a new geometry to this scene.
  23614. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23615. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23616. * @return {boolean} was the geometry added or not
  23617. */
  23618. Scene.prototype.pushGeometry = function (geometry, force) {
  23619. if (!force && this.getGeometryByID(geometry.id)) {
  23620. return false;
  23621. }
  23622. this._geometries.push(geometry);
  23623. //notify the collision coordinator
  23624. if (this.collisionCoordinator) {
  23625. this.collisionCoordinator.onGeometryAdded(geometry);
  23626. }
  23627. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23628. return true;
  23629. };
  23630. /**
  23631. * Removes an existing geometry
  23632. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23633. * @return {boolean} was the geometry removed or not
  23634. */
  23635. Scene.prototype.removeGeometry = function (geometry) {
  23636. var index = this._geometries.indexOf(geometry);
  23637. if (index > -1) {
  23638. this._geometries.splice(index, 1);
  23639. //notify the collision coordinator
  23640. if (this.collisionCoordinator) {
  23641. this.collisionCoordinator.onGeometryDeleted(geometry);
  23642. }
  23643. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23644. return true;
  23645. }
  23646. return false;
  23647. };
  23648. Scene.prototype.getGeometries = function () {
  23649. return this._geometries;
  23650. };
  23651. /**
  23652. * Get the first added mesh found of a given ID
  23653. * @param {string} id - the id to search for
  23654. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23655. */
  23656. Scene.prototype.getMeshByID = function (id) {
  23657. for (var index = 0; index < this.meshes.length; index++) {
  23658. if (this.meshes[index].id === id) {
  23659. return this.meshes[index];
  23660. }
  23661. }
  23662. return null;
  23663. };
  23664. Scene.prototype.getMeshesByID = function (id) {
  23665. return this.meshes.filter(function (m) {
  23666. return m.id === id;
  23667. });
  23668. };
  23669. /**
  23670. * Get the first added transform node found of a given ID
  23671. * @param {string} id - the id to search for
  23672. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23673. */
  23674. Scene.prototype.getTransformNodeByID = function (id) {
  23675. for (var index = 0; index < this.transformNodes.length; index++) {
  23676. if (this.transformNodes[index].id === id) {
  23677. return this.transformNodes[index];
  23678. }
  23679. }
  23680. return null;
  23681. };
  23682. Scene.prototype.getTransformNodesByID = function (id) {
  23683. return this.transformNodes.filter(function (m) {
  23684. return m.id === id;
  23685. });
  23686. };
  23687. /**
  23688. * Get a mesh with its auto-generated unique id
  23689. * @param {number} uniqueId - the unique id to search for
  23690. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23691. */
  23692. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23693. for (var index = 0; index < this.meshes.length; index++) {
  23694. if (this.meshes[index].uniqueId === uniqueId) {
  23695. return this.meshes[index];
  23696. }
  23697. }
  23698. return null;
  23699. };
  23700. /**
  23701. * Get a the last added mesh found of a given ID
  23702. * @param {string} id - the id to search for
  23703. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23704. */
  23705. Scene.prototype.getLastMeshByID = function (id) {
  23706. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23707. if (this.meshes[index].id === id) {
  23708. return this.meshes[index];
  23709. }
  23710. }
  23711. return null;
  23712. };
  23713. /**
  23714. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23715. * @param {string} id - the id to search for
  23716. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23717. */
  23718. Scene.prototype.getLastEntryByID = function (id) {
  23719. var index;
  23720. for (index = this.meshes.length - 1; index >= 0; index--) {
  23721. if (this.meshes[index].id === id) {
  23722. return this.meshes[index];
  23723. }
  23724. }
  23725. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23726. if (this.transformNodes[index].id === id) {
  23727. return this.transformNodes[index];
  23728. }
  23729. }
  23730. for (index = this.cameras.length - 1; index >= 0; index--) {
  23731. if (this.cameras[index].id === id) {
  23732. return this.cameras[index];
  23733. }
  23734. }
  23735. for (index = this.lights.length - 1; index >= 0; index--) {
  23736. if (this.lights[index].id === id) {
  23737. return this.lights[index];
  23738. }
  23739. }
  23740. return null;
  23741. };
  23742. Scene.prototype.getNodeByID = function (id) {
  23743. var mesh = this.getMeshByID(id);
  23744. if (mesh) {
  23745. return mesh;
  23746. }
  23747. var light = this.getLightByID(id);
  23748. if (light) {
  23749. return light;
  23750. }
  23751. var camera = this.getCameraByID(id);
  23752. if (camera) {
  23753. return camera;
  23754. }
  23755. var bone = this.getBoneByID(id);
  23756. return bone;
  23757. };
  23758. Scene.prototype.getNodeByName = function (name) {
  23759. var mesh = this.getMeshByName(name);
  23760. if (mesh) {
  23761. return mesh;
  23762. }
  23763. var light = this.getLightByName(name);
  23764. if (light) {
  23765. return light;
  23766. }
  23767. var camera = this.getCameraByName(name);
  23768. if (camera) {
  23769. return camera;
  23770. }
  23771. var bone = this.getBoneByName(name);
  23772. return bone;
  23773. };
  23774. Scene.prototype.getMeshByName = function (name) {
  23775. for (var index = 0; index < this.meshes.length; index++) {
  23776. if (this.meshes[index].name === name) {
  23777. return this.meshes[index];
  23778. }
  23779. }
  23780. return null;
  23781. };
  23782. Scene.prototype.getTransformNodeByName = function (name) {
  23783. for (var index = 0; index < this.transformNodes.length; index++) {
  23784. if (this.transformNodes[index].name === name) {
  23785. return this.transformNodes[index];
  23786. }
  23787. }
  23788. return null;
  23789. };
  23790. Scene.prototype.getSoundByName = function (name) {
  23791. var index;
  23792. if (BABYLON.AudioEngine) {
  23793. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23794. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23795. return this.mainSoundTrack.soundCollection[index];
  23796. }
  23797. }
  23798. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23799. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23800. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23801. return this.soundTracks[sdIndex].soundCollection[index];
  23802. }
  23803. }
  23804. }
  23805. }
  23806. return null;
  23807. };
  23808. Scene.prototype.getLastSkeletonByID = function (id) {
  23809. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23810. if (this.skeletons[index].id === id) {
  23811. return this.skeletons[index];
  23812. }
  23813. }
  23814. return null;
  23815. };
  23816. Scene.prototype.getSkeletonById = function (id) {
  23817. for (var index = 0; index < this.skeletons.length; index++) {
  23818. if (this.skeletons[index].id === id) {
  23819. return this.skeletons[index];
  23820. }
  23821. }
  23822. return null;
  23823. };
  23824. Scene.prototype.getSkeletonByName = function (name) {
  23825. for (var index = 0; index < this.skeletons.length; index++) {
  23826. if (this.skeletons[index].name === name) {
  23827. return this.skeletons[index];
  23828. }
  23829. }
  23830. return null;
  23831. };
  23832. Scene.prototype.getMorphTargetManagerById = function (id) {
  23833. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23834. if (this.morphTargetManagers[index].uniqueId === id) {
  23835. return this.morphTargetManagers[index];
  23836. }
  23837. }
  23838. return null;
  23839. };
  23840. Scene.prototype.isActiveMesh = function (mesh) {
  23841. return (this._activeMeshes.indexOf(mesh) !== -1);
  23842. };
  23843. /**
  23844. * Return a the first highlight layer of the scene with a given name.
  23845. * @param name The name of the highlight layer to look for.
  23846. * @return The highlight layer if found otherwise null.
  23847. */
  23848. Scene.prototype.getHighlightLayerByName = function (name) {
  23849. for (var index = 0; index < this.effectLayers.length; index++) {
  23850. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23851. return this.effectLayers[index];
  23852. }
  23853. }
  23854. return null;
  23855. };
  23856. /**
  23857. * Return a the first highlight layer of the scene with a given name.
  23858. * @param name The name of the highlight layer to look for.
  23859. * @return The highlight layer if found otherwise null.
  23860. */
  23861. Scene.prototype.getGlowLayerByName = function (name) {
  23862. for (var index = 0; index < this.effectLayers.length; index++) {
  23863. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23864. return this.effectLayers[index];
  23865. }
  23866. }
  23867. return null;
  23868. };
  23869. Object.defineProperty(Scene.prototype, "uid", {
  23870. /**
  23871. * Return a unique id as a string which can serve as an identifier for the scene
  23872. */
  23873. get: function () {
  23874. if (!this._uid) {
  23875. this._uid = BABYLON.Tools.RandomId();
  23876. }
  23877. return this._uid;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. /**
  23883. * Add an externaly attached data from its key.
  23884. * This method call will fail and return false, if such key already exists.
  23885. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23886. * @param key the unique key that identifies the data
  23887. * @param data the data object to associate to the key for this Engine instance
  23888. * @return true if no such key were already present and the data was added successfully, false otherwise
  23889. */
  23890. Scene.prototype.addExternalData = function (key, data) {
  23891. if (!this._externalData) {
  23892. this._externalData = new BABYLON.StringDictionary();
  23893. }
  23894. return this._externalData.add(key, data);
  23895. };
  23896. /**
  23897. * Get an externaly attached data from its key
  23898. * @param key the unique key that identifies the data
  23899. * @return the associated data, if present (can be null), or undefined if not present
  23900. */
  23901. Scene.prototype.getExternalData = function (key) {
  23902. if (!this._externalData) {
  23903. return null;
  23904. }
  23905. return this._externalData.get(key);
  23906. };
  23907. /**
  23908. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23909. * @param key the unique key that identifies the data
  23910. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23911. * @return the associated data, can be null if the factory returned null.
  23912. */
  23913. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23914. if (!this._externalData) {
  23915. this._externalData = new BABYLON.StringDictionary();
  23916. }
  23917. return this._externalData.getOrAddWithFactory(key, factory);
  23918. };
  23919. /**
  23920. * Remove an externaly attached data from the Engine instance
  23921. * @param key the unique key that identifies the data
  23922. * @return true if the data was successfully removed, false if it doesn't exist
  23923. */
  23924. Scene.prototype.removeExternalData = function (key) {
  23925. return this._externalData.remove(key);
  23926. };
  23927. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23928. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23929. if (mesh.showSubMeshesBoundingBox) {
  23930. var boundingInfo = subMesh.getBoundingInfo();
  23931. if (boundingInfo !== null && boundingInfo !== undefined) {
  23932. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23933. }
  23934. }
  23935. var material = subMesh.getMaterial();
  23936. if (material !== null && material !== undefined) {
  23937. // Render targets
  23938. if (material.getRenderTargetTextures !== undefined) {
  23939. if (this._processedMaterials.indexOf(material) === -1) {
  23940. this._processedMaterials.push(material);
  23941. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23942. }
  23943. }
  23944. // Dispatch
  23945. this._activeIndices.addCount(subMesh.indexCount, false);
  23946. this._renderingManager.dispatch(subMesh, mesh, material);
  23947. }
  23948. }
  23949. };
  23950. /**
  23951. * Clear the processed materials smart array preventing retention point in material dispose.
  23952. */
  23953. Scene.prototype.freeProcessedMaterials = function () {
  23954. this._processedMaterials.dispose();
  23955. };
  23956. /**
  23957. * Clear the active meshes smart array preventing retention point in mesh dispose.
  23958. */
  23959. Scene.prototype.freeActiveMeshes = function () {
  23960. this._activeMeshes.dispose();
  23961. if (this.activeCamera && this.activeCamera._activeMeshes) {
  23962. this.activeCamera._activeMeshes.dispose();
  23963. }
  23964. if (this.activeCameras) {
  23965. for (var i = 0; i < this.activeCameras.length; i++) {
  23966. var activeCamera = this.activeCameras[i];
  23967. if (activeCamera && activeCamera._activeMeshes) {
  23968. activeCamera._activeMeshes.dispose();
  23969. }
  23970. }
  23971. }
  23972. };
  23973. /**
  23974. * Clear the info related to rendering groups preventing retention points during dispose.
  23975. */
  23976. Scene.prototype.freeRenderingGroups = function () {
  23977. if (this._renderingManager) {
  23978. this._renderingManager.freeRenderingGroups();
  23979. }
  23980. if (this.textures) {
  23981. for (var i = 0; i < this.textures.length; i++) {
  23982. var texture = this.textures[i];
  23983. if (texture && texture.renderList) {
  23984. texture.freeRenderingGroups();
  23985. }
  23986. }
  23987. }
  23988. };
  23989. Scene.prototype._isInIntermediateRendering = function () {
  23990. return this._intermediateRendering;
  23991. };
  23992. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23993. this._activeMeshCandidateProvider = provider;
  23994. };
  23995. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23996. return this._activeMeshCandidateProvider;
  23997. };
  23998. /**
  23999. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24000. */
  24001. Scene.prototype.freezeActiveMeshes = function () {
  24002. if (!this.activeCamera) {
  24003. return this;
  24004. }
  24005. if (!this._frustumPlanes) {
  24006. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24007. }
  24008. this._evaluateActiveMeshes();
  24009. this._activeMeshesFrozen = true;
  24010. return this;
  24011. };
  24012. /**
  24013. * Use this function to restart evaluating active meshes on every frame
  24014. */
  24015. Scene.prototype.unfreezeActiveMeshes = function () {
  24016. this._activeMeshesFrozen = false;
  24017. return this;
  24018. };
  24019. Scene.prototype._evaluateActiveMeshes = function () {
  24020. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24021. return;
  24022. }
  24023. if (!this.activeCamera) {
  24024. return;
  24025. }
  24026. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24027. this.activeCamera._activeMeshes.reset();
  24028. this._activeMeshes.reset();
  24029. this._renderingManager.reset();
  24030. this._processedMaterials.reset();
  24031. this._activeParticleSystems.reset();
  24032. this._activeSkeletons.reset();
  24033. this._softwareSkinnedMeshes.reset();
  24034. if (this._boundingBoxRenderer) {
  24035. this._boundingBoxRenderer.reset();
  24036. }
  24037. // Meshes
  24038. var meshes;
  24039. var len;
  24040. var checkIsEnabled = true;
  24041. // Determine mesh candidates
  24042. if (this._activeMeshCandidateProvider !== undefined) {
  24043. // Use _activeMeshCandidateProvider
  24044. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24045. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24046. if (meshes !== undefined) {
  24047. len = meshes.length;
  24048. }
  24049. else {
  24050. len = 0;
  24051. }
  24052. }
  24053. else if (this._selectionOctree !== undefined) {
  24054. // Octree
  24055. var selection = this._selectionOctree.select(this._frustumPlanes);
  24056. meshes = selection.data;
  24057. len = selection.length;
  24058. }
  24059. else {
  24060. // Full scene traversal
  24061. len = this.meshes.length;
  24062. meshes = this.meshes;
  24063. }
  24064. // Check each mesh
  24065. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24066. mesh = meshes[meshIndex];
  24067. if (mesh.isBlocked) {
  24068. continue;
  24069. }
  24070. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24071. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24072. continue;
  24073. }
  24074. mesh.computeWorldMatrix();
  24075. // Intersections
  24076. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24077. this._meshesForIntersections.pushNoDuplicate(mesh);
  24078. }
  24079. // Switch to current LOD
  24080. meshLOD = mesh.getLOD(this.activeCamera);
  24081. if (meshLOD === undefined || meshLOD === null) {
  24082. continue;
  24083. }
  24084. mesh._preActivate();
  24085. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24086. this._activeMeshes.push(mesh);
  24087. this.activeCamera._activeMeshes.push(mesh);
  24088. mesh._activate(this._renderId);
  24089. if (meshLOD !== mesh) {
  24090. meshLOD._activate(this._renderId);
  24091. }
  24092. this._activeMesh(mesh, meshLOD);
  24093. }
  24094. }
  24095. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24096. // Particle systems
  24097. if (this.particlesEnabled) {
  24098. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24099. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24100. var particleSystem = this.particleSystems[particleIndex];
  24101. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24102. continue;
  24103. }
  24104. var emitter = particleSystem.emitter;
  24105. if (!emitter.position || emitter.isEnabled()) {
  24106. this._activeParticleSystems.push(particleSystem);
  24107. particleSystem.animate();
  24108. this._renderingManager.dispatchParticles(particleSystem);
  24109. }
  24110. }
  24111. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24112. }
  24113. };
  24114. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24115. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24116. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24117. mesh.skeleton.prepare();
  24118. }
  24119. if (!mesh.computeBonesUsingShaders) {
  24120. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24121. }
  24122. }
  24123. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24124. var boundingInfo = sourceMesh.getBoundingInfo();
  24125. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24126. }
  24127. if (mesh !== undefined && mesh !== null
  24128. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24129. // Submeshes Octrees
  24130. var len;
  24131. var subMeshes;
  24132. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24133. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24134. len = intersections.length;
  24135. subMeshes = intersections.data;
  24136. }
  24137. else {
  24138. subMeshes = mesh.subMeshes;
  24139. len = subMeshes.length;
  24140. }
  24141. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24142. subMesh = subMeshes[subIndex];
  24143. this._evaluateSubMesh(subMesh, mesh);
  24144. }
  24145. }
  24146. };
  24147. Scene.prototype.updateTransformMatrix = function (force) {
  24148. if (!this.activeCamera) {
  24149. return;
  24150. }
  24151. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24152. };
  24153. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24154. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24155. };
  24156. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24157. if (camera && camera._skipRendering) {
  24158. return;
  24159. }
  24160. var engine = this._engine;
  24161. this.activeCamera = camera;
  24162. if (!this.activeCamera)
  24163. throw new Error("Active camera not set");
  24164. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24165. // Viewport
  24166. engine.setViewport(this.activeCamera.viewport);
  24167. // Camera
  24168. this.resetCachedMaterial();
  24169. this._renderId++;
  24170. this.updateTransformMatrix();
  24171. if (camera._alternateCamera) {
  24172. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24173. this._alternateRendering = true;
  24174. }
  24175. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24176. // Meshes
  24177. this._evaluateActiveMeshes();
  24178. // Software skinning
  24179. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24180. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24181. mesh.applySkeleton(mesh.skeleton);
  24182. }
  24183. // Render targets
  24184. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24185. var needsRestoreFrameBuffer = false;
  24186. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24187. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24188. }
  24189. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24190. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24191. }
  24192. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24193. this._intermediateRendering = true;
  24194. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24195. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24196. var renderTarget = this._renderTargets.data[renderIndex];
  24197. if (renderTarget._shouldRender()) {
  24198. this._renderId++;
  24199. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24200. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24201. }
  24202. }
  24203. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24204. this._intermediateRendering = false;
  24205. this._renderId++;
  24206. needsRestoreFrameBuffer = true; // Restore back buffer
  24207. }
  24208. // Render EffecttLayer Texture
  24209. var stencilState = this._engine.getStencilBuffer();
  24210. var renderEffects = false;
  24211. var needStencil = false;
  24212. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24213. this._intermediateRendering = true;
  24214. for (var i = 0; i < this.effectLayers.length; i++) {
  24215. var effectLayer = this.effectLayers[i];
  24216. if (effectLayer.shouldRender() &&
  24217. (!effectLayer.camera ||
  24218. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24219. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24220. renderEffects = true;
  24221. needStencil = needStencil || effectLayer.needStencil();
  24222. var renderTarget = effectLayer._mainTexture;
  24223. if (renderTarget._shouldRender()) {
  24224. this._renderId++;
  24225. renderTarget.render(false, false);
  24226. needsRestoreFrameBuffer = true;
  24227. }
  24228. }
  24229. }
  24230. this._intermediateRendering = false;
  24231. this._renderId++;
  24232. }
  24233. if (needsRestoreFrameBuffer) {
  24234. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24235. }
  24236. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24237. // Prepare Frame
  24238. this.postProcessManager._prepareFrame();
  24239. // Backgrounds
  24240. var layerIndex;
  24241. var layer;
  24242. if (this.layers.length) {
  24243. engine.setDepthBuffer(false);
  24244. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24245. layer = this.layers[layerIndex];
  24246. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24247. layer.render();
  24248. }
  24249. }
  24250. engine.setDepthBuffer(true);
  24251. }
  24252. // Activate effect Layer stencil
  24253. if (needStencil) {
  24254. this._engine.setStencilBuffer(true);
  24255. }
  24256. // Render
  24257. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24258. this._renderingManager.render(null, null, true, true);
  24259. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24260. // Restore effect Layer stencil
  24261. if (needStencil) {
  24262. this._engine.setStencilBuffer(stencilState);
  24263. }
  24264. // Bounding boxes
  24265. if (this._boundingBoxRenderer) {
  24266. this._boundingBoxRenderer.render();
  24267. }
  24268. // Lens flares
  24269. if (this.lensFlaresEnabled) {
  24270. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24271. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24272. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24273. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24274. lensFlareSystem.render();
  24275. }
  24276. }
  24277. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24278. }
  24279. // Foregrounds
  24280. if (this.layers.length) {
  24281. engine.setDepthBuffer(false);
  24282. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24283. layer = this.layers[layerIndex];
  24284. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24285. layer.render();
  24286. }
  24287. }
  24288. engine.setDepthBuffer(true);
  24289. }
  24290. // Effect Layer
  24291. if (renderEffects) {
  24292. engine.setDepthBuffer(false);
  24293. for (var i = 0; i < this.effectLayers.length; i++) {
  24294. if (this.effectLayers[i].shouldRender()) {
  24295. this.effectLayers[i].render();
  24296. }
  24297. }
  24298. engine.setDepthBuffer(true);
  24299. }
  24300. // Finalize frame
  24301. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24302. // Reset some special arrays
  24303. this._renderTargets.reset();
  24304. this._alternateRendering = false;
  24305. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24306. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24307. };
  24308. Scene.prototype._processSubCameras = function (camera) {
  24309. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24310. this._renderForCamera(camera);
  24311. return;
  24312. }
  24313. // rig cameras
  24314. for (var index = 0; index < camera._rigCameras.length; index++) {
  24315. this._renderForCamera(camera._rigCameras[index], camera);
  24316. }
  24317. this.activeCamera = camera;
  24318. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24319. };
  24320. Scene.prototype._checkIntersections = function () {
  24321. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24322. var sourceMesh = this._meshesForIntersections.data[index];
  24323. if (!sourceMesh.actionManager) {
  24324. continue;
  24325. }
  24326. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24327. var action = sourceMesh.actionManager.actions[actionIndex];
  24328. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24329. var parameters = action.getTriggerParameter();
  24330. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24331. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24332. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24333. if (areIntersecting && currentIntersectionInProgress === -1) {
  24334. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24335. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24336. sourceMesh._intersectionsInProgress.push(otherMesh);
  24337. }
  24338. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24339. sourceMesh._intersectionsInProgress.push(otherMesh);
  24340. }
  24341. }
  24342. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24343. //They intersected, and now they don't.
  24344. //is this trigger an exit trigger? execute an event.
  24345. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24346. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24347. }
  24348. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24349. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24350. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24351. }
  24352. }
  24353. }
  24354. }
  24355. }
  24356. };
  24357. Scene.prototype.render = function () {
  24358. if (this.isDisposed) {
  24359. return;
  24360. }
  24361. this._activeParticles.fetchNewFrame();
  24362. this._totalVertices.fetchNewFrame();
  24363. this._activeIndices.fetchNewFrame();
  24364. this._activeBones.fetchNewFrame();
  24365. this._meshesForIntersections.reset();
  24366. this.resetCachedMaterial();
  24367. this.onBeforeAnimationsObservable.notifyObservers(this);
  24368. // Actions
  24369. if (this.actionManager) {
  24370. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24371. }
  24372. //Simplification Queue
  24373. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24374. this.simplificationQueue.executeNext();
  24375. }
  24376. if (this._engine.isDeterministicLockStep()) {
  24377. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24378. var defaultFPS = (60.0 / 1000.0);
  24379. var defaultFrameTime = 1000 / 60; // frame time in MS
  24380. if (this._physicsEngine) {
  24381. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24382. }
  24383. var stepsTaken = 0;
  24384. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24385. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24386. internalSteps = Math.min(internalSteps, maxSubSteps);
  24387. do {
  24388. this.onBeforeStepObservable.notifyObservers(this);
  24389. // Animations
  24390. this._animationRatio = defaultFrameTime * defaultFPS;
  24391. this._animate();
  24392. this.onAfterAnimationsObservable.notifyObservers(this);
  24393. // Physics
  24394. if (this._physicsEngine) {
  24395. this.onBeforePhysicsObservable.notifyObservers(this);
  24396. this._physicsEngine._step(defaultFrameTime / 1000);
  24397. this.onAfterPhysicsObservable.notifyObservers(this);
  24398. }
  24399. this.onAfterStepObservable.notifyObservers(this);
  24400. this._currentStepId++;
  24401. stepsTaken++;
  24402. deltaTime -= defaultFrameTime;
  24403. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24404. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24405. }
  24406. else {
  24407. // Animations
  24408. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24409. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24410. this._animate();
  24411. this.onAfterAnimationsObservable.notifyObservers(this);
  24412. // Physics
  24413. if (this._physicsEngine) {
  24414. this.onBeforePhysicsObservable.notifyObservers(this);
  24415. this._physicsEngine._step(deltaTime / 1000.0);
  24416. this.onAfterPhysicsObservable.notifyObservers(this);
  24417. }
  24418. }
  24419. // update gamepad manager
  24420. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24421. this._gamepadManager._checkGamepadsStatus();
  24422. }
  24423. // Update Cameras
  24424. if (this.activeCameras.length > 0) {
  24425. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24426. var camera = this.activeCameras[cameraIndex];
  24427. camera.update();
  24428. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24429. // rig cameras
  24430. for (var index = 0; index < camera._rigCameras.length; index++) {
  24431. camera._rigCameras[index].update();
  24432. }
  24433. }
  24434. }
  24435. }
  24436. else if (this.activeCamera) {
  24437. this.activeCamera.update();
  24438. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24439. // rig cameras
  24440. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24441. this.activeCamera._rigCameras[index].update();
  24442. }
  24443. }
  24444. }
  24445. // Before render
  24446. this.onBeforeRenderObservable.notifyObservers(this);
  24447. // Customs render targets
  24448. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24449. var engine = this.getEngine();
  24450. var currentActiveCamera = this.activeCamera;
  24451. if (this.renderTargetsEnabled) {
  24452. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24453. this._intermediateRendering = true;
  24454. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24455. var renderTarget = this.customRenderTargets[customIndex];
  24456. if (renderTarget._shouldRender()) {
  24457. this._renderId++;
  24458. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24459. if (!this.activeCamera)
  24460. throw new Error("Active camera not set");
  24461. // Viewport
  24462. engine.setViewport(this.activeCamera.viewport);
  24463. // Camera
  24464. this.updateTransformMatrix();
  24465. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24466. }
  24467. }
  24468. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24469. this._intermediateRendering = false;
  24470. this._renderId++;
  24471. }
  24472. // Restore back buffer
  24473. if (this.customRenderTargets.length > 0) {
  24474. engine.restoreDefaultFramebuffer();
  24475. }
  24476. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24477. this.activeCamera = currentActiveCamera;
  24478. // Procedural textures
  24479. if (this.proceduralTexturesEnabled) {
  24480. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24481. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24482. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24483. if (proceduralTexture._shouldRender()) {
  24484. proceduralTexture.render();
  24485. }
  24486. }
  24487. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24488. }
  24489. // Clear
  24490. if (this.autoClearDepthAndStencil || this.autoClear) {
  24491. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24492. }
  24493. // Shadows
  24494. if (this.shadowsEnabled) {
  24495. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24496. var light = this.lights[lightIndex];
  24497. var shadowGenerator = light.getShadowGenerator();
  24498. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24499. var shadowMap = (shadowGenerator.getShadowMap());
  24500. if (this.textures.indexOf(shadowMap) !== -1) {
  24501. this._renderTargets.push(shadowMap);
  24502. }
  24503. }
  24504. }
  24505. }
  24506. // Depth renderer
  24507. for (var key in this._depthRenderer) {
  24508. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24509. }
  24510. // Geometry renderer
  24511. if (this._geometryBufferRenderer) {
  24512. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24513. }
  24514. // RenderPipeline
  24515. if (this._postProcessRenderPipelineManager) {
  24516. this._postProcessRenderPipelineManager.update();
  24517. }
  24518. // Multi-cameras?
  24519. if (this.activeCameras.length > 0) {
  24520. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24521. if (cameraIndex > 0) {
  24522. this._engine.clear(null, false, true, true);
  24523. }
  24524. this._processSubCameras(this.activeCameras[cameraIndex]);
  24525. }
  24526. }
  24527. else {
  24528. if (!this.activeCamera) {
  24529. throw new Error("No camera defined");
  24530. }
  24531. this._processSubCameras(this.activeCamera);
  24532. }
  24533. // Intersection checks
  24534. this._checkIntersections();
  24535. // Update the audio listener attached to the camera
  24536. if (BABYLON.AudioEngine) {
  24537. this._updateAudioParameters();
  24538. }
  24539. // After render
  24540. if (this.afterRender) {
  24541. this.afterRender();
  24542. }
  24543. this.onAfterRenderObservable.notifyObservers(this);
  24544. // Cleaning
  24545. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24546. var data = this._toBeDisposed.data[index];
  24547. if (data) {
  24548. data.dispose();
  24549. }
  24550. this._toBeDisposed[index] = null;
  24551. }
  24552. this._toBeDisposed.reset();
  24553. if (this.dumpNextRenderTargets) {
  24554. this.dumpNextRenderTargets = false;
  24555. }
  24556. this._activeBones.addCount(0, true);
  24557. this._activeIndices.addCount(0, true);
  24558. this._activeParticles.addCount(0, true);
  24559. };
  24560. Scene.prototype._updateAudioParameters = function () {
  24561. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24562. return;
  24563. }
  24564. var listeningCamera;
  24565. var audioEngine = BABYLON.Engine.audioEngine;
  24566. if (this.activeCameras.length > 0) {
  24567. listeningCamera = this.activeCameras[0];
  24568. }
  24569. else {
  24570. listeningCamera = this.activeCamera;
  24571. }
  24572. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24573. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24574. // for VR cameras
  24575. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24576. listeningCamera = listeningCamera.rigCameras[0];
  24577. }
  24578. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24579. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24580. cameraDirection.normalize();
  24581. // To avoid some errors on GearVR
  24582. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24583. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24584. }
  24585. var i;
  24586. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24587. var sound = this.mainSoundTrack.soundCollection[i];
  24588. if (sound.useCustomAttenuation) {
  24589. sound.updateDistanceFromListener();
  24590. }
  24591. }
  24592. for (i = 0; i < this.soundTracks.length; i++) {
  24593. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24594. sound = this.soundTracks[i].soundCollection[j];
  24595. if (sound.useCustomAttenuation) {
  24596. sound.updateDistanceFromListener();
  24597. }
  24598. }
  24599. }
  24600. }
  24601. };
  24602. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24603. // Audio
  24604. get: function () {
  24605. return this._audioEnabled;
  24606. },
  24607. set: function (value) {
  24608. this._audioEnabled = value;
  24609. if (BABYLON.AudioEngine) {
  24610. if (this._audioEnabled) {
  24611. this._enableAudio();
  24612. }
  24613. else {
  24614. this._disableAudio();
  24615. }
  24616. }
  24617. },
  24618. enumerable: true,
  24619. configurable: true
  24620. });
  24621. Scene.prototype._disableAudio = function () {
  24622. var i;
  24623. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24624. this.mainSoundTrack.soundCollection[i].pause();
  24625. }
  24626. for (i = 0; i < this.soundTracks.length; i++) {
  24627. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24628. this.soundTracks[i].soundCollection[j].pause();
  24629. }
  24630. }
  24631. };
  24632. Scene.prototype._enableAudio = function () {
  24633. var i;
  24634. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24635. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24636. this.mainSoundTrack.soundCollection[i].play();
  24637. }
  24638. }
  24639. for (i = 0; i < this.soundTracks.length; i++) {
  24640. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24641. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24642. this.soundTracks[i].soundCollection[j].play();
  24643. }
  24644. }
  24645. }
  24646. };
  24647. Object.defineProperty(Scene.prototype, "headphone", {
  24648. get: function () {
  24649. return this._headphone;
  24650. },
  24651. set: function (value) {
  24652. this._headphone = value;
  24653. if (BABYLON.AudioEngine) {
  24654. if (this._headphone) {
  24655. this._switchAudioModeForHeadphones();
  24656. }
  24657. else {
  24658. this._switchAudioModeForNormalSpeakers();
  24659. }
  24660. }
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. Scene.prototype._switchAudioModeForHeadphones = function () {
  24666. this.mainSoundTrack.switchPanningModelToHRTF();
  24667. for (var i = 0; i < this.soundTracks.length; i++) {
  24668. this.soundTracks[i].switchPanningModelToHRTF();
  24669. }
  24670. };
  24671. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24672. this.mainSoundTrack.switchPanningModelToEqualPower();
  24673. for (var i = 0; i < this.soundTracks.length; i++) {
  24674. this.soundTracks[i].switchPanningModelToEqualPower();
  24675. }
  24676. };
  24677. /**
  24678. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24679. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24680. * @returns the created depth renderer
  24681. */
  24682. Scene.prototype.enableDepthRenderer = function (camera) {
  24683. camera = camera || this.activeCamera;
  24684. if (!camera) {
  24685. throw "No camera available to enable depth renderer";
  24686. }
  24687. if (!this._depthRenderer[camera.id]) {
  24688. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24689. }
  24690. return this._depthRenderer[camera.id];
  24691. };
  24692. /**
  24693. * Disables a depth renderer for a given camera
  24694. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24695. */
  24696. Scene.prototype.disableDepthRenderer = function (camera) {
  24697. camera = camera || this.activeCamera;
  24698. if (!camera || !this._depthRenderer[camera.id]) {
  24699. return;
  24700. }
  24701. this._depthRenderer[camera.id].dispose();
  24702. delete this._depthRenderer[camera.id];
  24703. };
  24704. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24705. if (ratio === void 0) { ratio = 1; }
  24706. if (this._geometryBufferRenderer) {
  24707. return this._geometryBufferRenderer;
  24708. }
  24709. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24710. if (!this._geometryBufferRenderer.isSupported) {
  24711. this._geometryBufferRenderer = null;
  24712. }
  24713. return this._geometryBufferRenderer;
  24714. };
  24715. Scene.prototype.disableGeometryBufferRenderer = function () {
  24716. if (!this._geometryBufferRenderer) {
  24717. return;
  24718. }
  24719. this._geometryBufferRenderer.dispose();
  24720. this._geometryBufferRenderer = null;
  24721. };
  24722. Scene.prototype.freezeMaterials = function () {
  24723. for (var i = 0; i < this.materials.length; i++) {
  24724. this.materials[i].freeze();
  24725. }
  24726. };
  24727. Scene.prototype.unfreezeMaterials = function () {
  24728. for (var i = 0; i < this.materials.length; i++) {
  24729. this.materials[i].unfreeze();
  24730. }
  24731. };
  24732. Scene.prototype.dispose = function () {
  24733. this.beforeRender = null;
  24734. this.afterRender = null;
  24735. this.skeletons = [];
  24736. this.morphTargetManagers = [];
  24737. this.importedMeshesFiles = new Array();
  24738. this.stopAllAnimations();
  24739. this.resetCachedMaterial();
  24740. for (var key in this._depthRenderer) {
  24741. this._depthRenderer[key].dispose();
  24742. }
  24743. if (this._gamepadManager) {
  24744. this._gamepadManager.dispose();
  24745. this._gamepadManager = null;
  24746. }
  24747. // Smart arrays
  24748. if (this.activeCamera) {
  24749. this.activeCamera._activeMeshes.dispose();
  24750. this.activeCamera = null;
  24751. }
  24752. this._activeMeshes.dispose();
  24753. this._renderingManager.dispose();
  24754. this._processedMaterials.dispose();
  24755. this._activeParticleSystems.dispose();
  24756. this._activeSkeletons.dispose();
  24757. this._softwareSkinnedMeshes.dispose();
  24758. this._renderTargets.dispose();
  24759. if (this._boundingBoxRenderer) {
  24760. this._boundingBoxRenderer.dispose();
  24761. }
  24762. this._meshesForIntersections.dispose();
  24763. this._toBeDisposed.dispose();
  24764. // Abort active requests
  24765. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24766. var request = _a[_i];
  24767. request.abort();
  24768. }
  24769. // Debug layer
  24770. if (this._debugLayer) {
  24771. this._debugLayer.hide();
  24772. }
  24773. // Events
  24774. this.onDisposeObservable.notifyObservers(this);
  24775. this.onDisposeObservable.clear();
  24776. this.onBeforeRenderObservable.clear();
  24777. this.onAfterRenderObservable.clear();
  24778. this.OnBeforeRenderTargetsRenderObservable.clear();
  24779. this.OnAfterRenderTargetsRenderObservable.clear();
  24780. this.onAfterStepObservable.clear();
  24781. this.onBeforeStepObservable.clear();
  24782. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24783. this.onAfterActiveMeshesEvaluationObservable.clear();
  24784. this.onBeforeParticlesRenderingObservable.clear();
  24785. this.onAfterParticlesRenderingObservable.clear();
  24786. this.onBeforeSpritesRenderingObservable.clear();
  24787. this.onAfterSpritesRenderingObservable.clear();
  24788. this.onBeforeDrawPhaseObservable.clear();
  24789. this.onAfterDrawPhaseObservable.clear();
  24790. this.onBeforePhysicsObservable.clear();
  24791. this.onAfterPhysicsObservable.clear();
  24792. this.onBeforeAnimationsObservable.clear();
  24793. this.onAfterAnimationsObservable.clear();
  24794. this.onDataLoadedObservable.clear();
  24795. this.detachControl();
  24796. // Release sounds & sounds tracks
  24797. if (BABYLON.AudioEngine) {
  24798. this.disposeSounds();
  24799. }
  24800. // VR Helper
  24801. if (this.VRHelper) {
  24802. this.VRHelper.dispose();
  24803. }
  24804. // Detach cameras
  24805. var canvas = this._engine.getRenderingCanvas();
  24806. if (canvas) {
  24807. var index;
  24808. for (index = 0; index < this.cameras.length; index++) {
  24809. this.cameras[index].detachControl(canvas);
  24810. }
  24811. }
  24812. // Release animation groups
  24813. while (this.animationGroups.length) {
  24814. this.animationGroups[0].dispose();
  24815. }
  24816. // Release lights
  24817. while (this.lights.length) {
  24818. this.lights[0].dispose();
  24819. }
  24820. // Release meshes
  24821. while (this.meshes.length) {
  24822. this.meshes[0].dispose(true);
  24823. }
  24824. while (this.transformNodes.length) {
  24825. this.removeTransformNode(this.transformNodes[0]);
  24826. }
  24827. // Release cameras
  24828. while (this.cameras.length) {
  24829. this.cameras[0].dispose();
  24830. }
  24831. // Release materials
  24832. if (this.defaultMaterial) {
  24833. this.defaultMaterial.dispose();
  24834. }
  24835. while (this.multiMaterials.length) {
  24836. this.multiMaterials[0].dispose();
  24837. }
  24838. while (this.materials.length) {
  24839. this.materials[0].dispose();
  24840. }
  24841. // Release particles
  24842. while (this.particleSystems.length) {
  24843. this.particleSystems[0].dispose();
  24844. }
  24845. // Release sprites
  24846. while (this.spriteManagers.length) {
  24847. this.spriteManagers[0].dispose();
  24848. }
  24849. // Release postProcesses
  24850. while (this.postProcesses.length) {
  24851. this.postProcesses[0].dispose();
  24852. }
  24853. // Release layers
  24854. while (this.layers.length) {
  24855. this.layers[0].dispose();
  24856. }
  24857. while (this.effectLayers.length) {
  24858. this.effectLayers[0].dispose();
  24859. }
  24860. // Release textures
  24861. while (this.textures.length) {
  24862. this.textures[0].dispose();
  24863. }
  24864. // Release UBO
  24865. this._sceneUbo.dispose();
  24866. if (this._alternateSceneUbo) {
  24867. this._alternateSceneUbo.dispose();
  24868. }
  24869. // Post-processes
  24870. this.postProcessManager.dispose();
  24871. if (this._postProcessRenderPipelineManager) {
  24872. this._postProcessRenderPipelineManager.dispose();
  24873. }
  24874. // Physics
  24875. if (this._physicsEngine) {
  24876. this.disablePhysicsEngine();
  24877. }
  24878. // Remove from engine
  24879. index = this._engine.scenes.indexOf(this);
  24880. if (index > -1) {
  24881. this._engine.scenes.splice(index, 1);
  24882. }
  24883. this._engine.wipeCaches(true);
  24884. this._isDisposed = true;
  24885. };
  24886. Object.defineProperty(Scene.prototype, "isDisposed", {
  24887. get: function () {
  24888. return this._isDisposed;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. // Release sounds & sounds tracks
  24894. Scene.prototype.disposeSounds = function () {
  24895. if (!this._mainSoundTrack) {
  24896. return;
  24897. }
  24898. this.mainSoundTrack.dispose();
  24899. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24900. this.soundTracks[scIndex].dispose();
  24901. }
  24902. };
  24903. // Octrees
  24904. /**
  24905. * Get the world extend vectors with an optional filter
  24906. *
  24907. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24908. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24909. */
  24910. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24911. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24912. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24913. filterPredicate = filterPredicate || (function () { return true; });
  24914. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24915. mesh.computeWorldMatrix(true);
  24916. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24917. return;
  24918. }
  24919. var boundingInfo = mesh.getBoundingInfo();
  24920. var minBox = boundingInfo.boundingBox.minimumWorld;
  24921. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24922. BABYLON.Tools.CheckExtends(minBox, min, max);
  24923. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24924. });
  24925. return {
  24926. min: min,
  24927. max: max
  24928. };
  24929. };
  24930. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24931. if (maxCapacity === void 0) { maxCapacity = 64; }
  24932. if (maxDepth === void 0) { maxDepth = 2; }
  24933. if (!this._selectionOctree) {
  24934. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24935. }
  24936. var worldExtends = this.getWorldExtends();
  24937. // Update octree
  24938. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24939. return this._selectionOctree;
  24940. };
  24941. // Picking
  24942. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24943. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24944. var result = BABYLON.Ray.Zero();
  24945. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24946. return result;
  24947. };
  24948. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24949. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24950. var engine = this._engine;
  24951. if (!camera) {
  24952. if (!this.activeCamera)
  24953. throw new Error("Active camera not set");
  24954. camera = this.activeCamera;
  24955. }
  24956. var cameraViewport = camera.viewport;
  24957. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24958. // Moving coordinates to local viewport world
  24959. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24960. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24961. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24962. return this;
  24963. };
  24964. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24965. var result = BABYLON.Ray.Zero();
  24966. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24967. return result;
  24968. };
  24969. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24970. if (!BABYLON.PickingInfo) {
  24971. return this;
  24972. }
  24973. var engine = this._engine;
  24974. if (!camera) {
  24975. if (!this.activeCamera)
  24976. throw new Error("Active camera not set");
  24977. camera = this.activeCamera;
  24978. }
  24979. var cameraViewport = camera.viewport;
  24980. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24981. var identity = BABYLON.Matrix.Identity();
  24982. // Moving coordinates to local viewport world
  24983. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24984. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24985. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24986. return this;
  24987. };
  24988. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24989. if (!BABYLON.PickingInfo) {
  24990. return null;
  24991. }
  24992. var pickingInfo = null;
  24993. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24994. var mesh = this.meshes[meshIndex];
  24995. if (predicate) {
  24996. if (!predicate(mesh)) {
  24997. continue;
  24998. }
  24999. }
  25000. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25001. continue;
  25002. }
  25003. var world = mesh.getWorldMatrix();
  25004. var ray = rayFunction(world);
  25005. var result = mesh.intersects(ray, fastCheck);
  25006. if (!result || !result.hit)
  25007. continue;
  25008. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25009. continue;
  25010. pickingInfo = result;
  25011. if (fastCheck) {
  25012. break;
  25013. }
  25014. }
  25015. return pickingInfo || new BABYLON.PickingInfo();
  25016. };
  25017. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25018. if (!BABYLON.PickingInfo) {
  25019. return null;
  25020. }
  25021. var pickingInfos = new Array();
  25022. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25023. var mesh = this.meshes[meshIndex];
  25024. if (predicate) {
  25025. if (!predicate(mesh)) {
  25026. continue;
  25027. }
  25028. }
  25029. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25030. continue;
  25031. }
  25032. var world = mesh.getWorldMatrix();
  25033. var ray = rayFunction(world);
  25034. var result = mesh.intersects(ray, false);
  25035. if (!result || !result.hit)
  25036. continue;
  25037. pickingInfos.push(result);
  25038. }
  25039. return pickingInfos;
  25040. };
  25041. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25042. if (!BABYLON.PickingInfo) {
  25043. return null;
  25044. }
  25045. var pickingInfo = null;
  25046. if (!camera) {
  25047. if (!this.activeCamera) {
  25048. return null;
  25049. }
  25050. camera = this.activeCamera;
  25051. }
  25052. if (this.spriteManagers.length > 0) {
  25053. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25054. var spriteManager = this.spriteManagers[spriteIndex];
  25055. if (!spriteManager.isPickable) {
  25056. continue;
  25057. }
  25058. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25059. if (!result || !result.hit)
  25060. continue;
  25061. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25062. continue;
  25063. pickingInfo = result;
  25064. if (fastCheck) {
  25065. break;
  25066. }
  25067. }
  25068. }
  25069. return pickingInfo || new BABYLON.PickingInfo();
  25070. };
  25071. /** Launch a ray to try to pick a mesh in the scene
  25072. * @param x position on screen
  25073. * @param y position on screen
  25074. * @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
  25075. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25076. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25077. */
  25078. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25079. var _this = this;
  25080. if (!BABYLON.PickingInfo) {
  25081. return null;
  25082. }
  25083. return this._internalPick(function (world) {
  25084. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25085. return _this._tempPickingRay;
  25086. }, predicate, fastCheck);
  25087. };
  25088. /** Launch a ray to try to pick a sprite in the scene
  25089. * @param x position on screen
  25090. * @param y position on screen
  25091. * @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
  25092. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25093. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25094. */
  25095. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25096. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25097. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25098. };
  25099. /** Use the given ray to pick a mesh in the scene
  25100. * @param ray The ray to use to pick meshes
  25101. * @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
  25102. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25103. */
  25104. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25105. var _this = this;
  25106. return this._internalPick(function (world) {
  25107. if (!_this._pickWithRayInverseMatrix) {
  25108. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25109. }
  25110. world.invertToRef(_this._pickWithRayInverseMatrix);
  25111. if (!_this._cachedRayForTransform) {
  25112. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25113. }
  25114. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25115. return _this._cachedRayForTransform;
  25116. }, predicate, fastCheck);
  25117. };
  25118. /**
  25119. * Launch a ray to try to pick a mesh in the scene
  25120. * @param x X position on screen
  25121. * @param y Y position on screen
  25122. * @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
  25123. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25124. */
  25125. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25126. var _this = this;
  25127. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25128. };
  25129. /**
  25130. * Launch a ray to try to pick a mesh in the scene
  25131. * @param ray Ray to use
  25132. * @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
  25133. */
  25134. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25135. var _this = this;
  25136. return this._internalMultiPick(function (world) {
  25137. if (!_this._pickWithRayInverseMatrix) {
  25138. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25139. }
  25140. world.invertToRef(_this._pickWithRayInverseMatrix);
  25141. if (!_this._cachedRayForTransform) {
  25142. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25143. }
  25144. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25145. return _this._cachedRayForTransform;
  25146. }, predicate);
  25147. };
  25148. Scene.prototype.setPointerOverMesh = function (mesh) {
  25149. if (this._pointerOverMesh === mesh) {
  25150. return;
  25151. }
  25152. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25153. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25154. }
  25155. this._pointerOverMesh = mesh;
  25156. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25157. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25158. }
  25159. };
  25160. Scene.prototype.getPointerOverMesh = function () {
  25161. return this._pointerOverMesh;
  25162. };
  25163. Scene.prototype.setPointerOverSprite = function (sprite) {
  25164. if (this._pointerOverSprite === sprite) {
  25165. return;
  25166. }
  25167. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25168. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25169. }
  25170. this._pointerOverSprite = sprite;
  25171. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25172. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25173. }
  25174. };
  25175. Scene.prototype.getPointerOverSprite = function () {
  25176. return this._pointerOverSprite;
  25177. };
  25178. // Physics
  25179. Scene.prototype.getPhysicsEngine = function () {
  25180. return this._physicsEngine;
  25181. };
  25182. /**
  25183. * Enables physics to the current scene
  25184. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25185. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25186. * @return {boolean} was the physics engine initialized
  25187. */
  25188. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25189. if (gravity === void 0) { gravity = null; }
  25190. if (this._physicsEngine) {
  25191. return true;
  25192. }
  25193. try {
  25194. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25195. return true;
  25196. }
  25197. catch (e) {
  25198. BABYLON.Tools.Error(e.message);
  25199. return false;
  25200. }
  25201. };
  25202. Scene.prototype.disablePhysicsEngine = function () {
  25203. if (!this._physicsEngine) {
  25204. return;
  25205. }
  25206. this._physicsEngine.dispose();
  25207. this._physicsEngine = null;
  25208. };
  25209. Scene.prototype.isPhysicsEnabled = function () {
  25210. return this._physicsEngine !== undefined;
  25211. };
  25212. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25213. var mesh = compound.parts[0].mesh;
  25214. if (mesh.physicsImpostor) {
  25215. mesh.physicsImpostor.dispose();
  25216. mesh.physicsImpostor = null;
  25217. }
  25218. };
  25219. // Misc.
  25220. Scene.prototype._rebuildGeometries = function () {
  25221. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25222. var geometry = _a[_i];
  25223. geometry._rebuild();
  25224. }
  25225. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25226. var mesh = _c[_b];
  25227. mesh._rebuild();
  25228. }
  25229. if (this.postProcessManager) {
  25230. this.postProcessManager._rebuild();
  25231. }
  25232. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25233. var layer = _e[_d];
  25234. layer._rebuild();
  25235. }
  25236. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25237. var effectLayer = _g[_f];
  25238. effectLayer._rebuild();
  25239. }
  25240. if (this._boundingBoxRenderer) {
  25241. this._boundingBoxRenderer._rebuild();
  25242. }
  25243. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25244. var system = _j[_h];
  25245. system.rebuild();
  25246. }
  25247. if (this._postProcessRenderPipelineManager) {
  25248. this._postProcessRenderPipelineManager._rebuild();
  25249. }
  25250. };
  25251. Scene.prototype._rebuildTextures = function () {
  25252. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25253. var texture = _a[_i];
  25254. texture._rebuild();
  25255. }
  25256. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25257. };
  25258. /**
  25259. * Creates a default light for the scene.
  25260. * @param replace Whether to replace the existing lights in the scene.
  25261. */
  25262. Scene.prototype.createDefaultLight = function (replace) {
  25263. if (replace === void 0) { replace = false; }
  25264. // Dispose existing light in replace mode.
  25265. if (replace) {
  25266. if (this.lights) {
  25267. for (var i = 0; i < this.lights.length; i++) {
  25268. this.lights[i].dispose();
  25269. }
  25270. }
  25271. }
  25272. // Light
  25273. if (this.lights.length === 0) {
  25274. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25275. }
  25276. };
  25277. /**
  25278. * Creates a default camera for the scene.
  25279. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25280. * @param replace Whether to replace the existing active camera in the scene.
  25281. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25282. */
  25283. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25284. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25285. if (replace === void 0) { replace = false; }
  25286. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25287. // Dispose existing camera in replace mode.
  25288. if (replace) {
  25289. if (this.activeCamera) {
  25290. this.activeCamera.dispose();
  25291. this.activeCamera = null;
  25292. }
  25293. }
  25294. // Camera
  25295. if (!this.activeCamera) {
  25296. var worldExtends = this.getWorldExtends();
  25297. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25298. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25299. var camera;
  25300. var radius = worldSize.length() * 1.5;
  25301. // empty scene scenario!
  25302. if (!isFinite(radius)) {
  25303. radius = 1;
  25304. worldCenter.copyFromFloats(0, 0, 0);
  25305. }
  25306. if (createArcRotateCamera) {
  25307. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25308. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25309. arcRotateCamera.wheelPrecision = 100 / radius;
  25310. camera = arcRotateCamera;
  25311. }
  25312. else {
  25313. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25314. freeCamera.setTarget(worldCenter);
  25315. camera = freeCamera;
  25316. }
  25317. camera.minZ = radius * 0.01;
  25318. camera.maxZ = radius * 1000;
  25319. camera.speed = radius * 0.2;
  25320. this.activeCamera = camera;
  25321. var canvas = this.getEngine().getRenderingCanvas();
  25322. if (attachCameraControls && canvas) {
  25323. camera.attachControl(canvas);
  25324. }
  25325. }
  25326. };
  25327. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25328. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25329. if (replace === void 0) { replace = false; }
  25330. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25331. this.createDefaultLight(replace);
  25332. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25333. };
  25334. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25335. if (pbr === void 0) { pbr = false; }
  25336. if (scale === void 0) { scale = 1000; }
  25337. if (blur === void 0) { blur = 0; }
  25338. if (environmentTexture) {
  25339. this.environmentTexture = environmentTexture;
  25340. }
  25341. if (!this.environmentTexture) {
  25342. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25343. return null;
  25344. }
  25345. // Skybox
  25346. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25347. if (pbr) {
  25348. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25349. hdrSkyboxMaterial.backFaceCulling = false;
  25350. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25351. if (hdrSkyboxMaterial.reflectionTexture) {
  25352. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25353. }
  25354. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25355. hdrSkyboxMaterial.disableLighting = true;
  25356. hdrSkyboxMaterial.twoSidedLighting = true;
  25357. hdrSkybox.infiniteDistance = true;
  25358. hdrSkybox.material = hdrSkyboxMaterial;
  25359. }
  25360. else {
  25361. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25362. skyboxMaterial.backFaceCulling = false;
  25363. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25364. if (skyboxMaterial.reflectionTexture) {
  25365. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25366. }
  25367. skyboxMaterial.disableLighting = true;
  25368. hdrSkybox.infiniteDistance = true;
  25369. hdrSkybox.material = skyboxMaterial;
  25370. }
  25371. return hdrSkybox;
  25372. };
  25373. Scene.prototype.createDefaultEnvironment = function (options) {
  25374. if (BABYLON.EnvironmentHelper) {
  25375. return new BABYLON.EnvironmentHelper(options, this);
  25376. }
  25377. return null;
  25378. };
  25379. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25380. if (webVROptions === void 0) { webVROptions = {}; }
  25381. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25382. };
  25383. // Tags
  25384. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25385. if (tagsQuery === undefined) {
  25386. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25387. return list;
  25388. }
  25389. var listByTags = [];
  25390. forEach = forEach || (function (item) { return; });
  25391. for (var i in list) {
  25392. var item = list[i];
  25393. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25394. listByTags.push(item);
  25395. forEach(item);
  25396. }
  25397. }
  25398. return listByTags;
  25399. };
  25400. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25401. return this._getByTags(this.meshes, tagsQuery, forEach);
  25402. };
  25403. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25404. return this._getByTags(this.cameras, tagsQuery, forEach);
  25405. };
  25406. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25407. return this._getByTags(this.lights, tagsQuery, forEach);
  25408. };
  25409. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25410. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25411. };
  25412. /**
  25413. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25414. * This allowed control for front to back rendering or reversly depending of the special needs.
  25415. *
  25416. * @param renderingGroupId The rendering group id corresponding to its index
  25417. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25418. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25419. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25420. */
  25421. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25422. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25423. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25424. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25425. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25426. };
  25427. /**
  25428. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25429. *
  25430. * @param renderingGroupId The rendering group id corresponding to its index
  25431. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25432. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25433. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25434. */
  25435. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25436. if (depth === void 0) { depth = true; }
  25437. if (stencil === void 0) { stencil = true; }
  25438. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25439. };
  25440. /**
  25441. * Will flag all materials as dirty to trigger new shader compilation
  25442. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25443. */
  25444. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25445. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25446. var material = _a[_i];
  25447. if (predicate && !predicate(material)) {
  25448. continue;
  25449. }
  25450. material.markAsDirty(flag);
  25451. }
  25452. };
  25453. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25454. var _this = this;
  25455. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25456. this._activeRequests.push(request);
  25457. request.onCompleteObservable.add(function (request) {
  25458. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25459. });
  25460. return request;
  25461. };
  25462. /** @ignore */
  25463. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25464. var _this = this;
  25465. return new Promise(function (resolve, reject) {
  25466. _this._loadFile(url, function (data) {
  25467. resolve(data);
  25468. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25469. reject(exception);
  25470. });
  25471. });
  25472. };
  25473. // Statics
  25474. Scene._FOGMODE_NONE = 0;
  25475. Scene._FOGMODE_EXP = 1;
  25476. Scene._FOGMODE_EXP2 = 2;
  25477. Scene._FOGMODE_LINEAR = 3;
  25478. Scene._uniqueIdCounter = 0;
  25479. Scene.MinDeltaTime = 1.0;
  25480. Scene.MaxDeltaTime = 1000.0;
  25481. /** The distance in pixel that you have to move to prevent some events */
  25482. Scene.DragMovementThreshold = 10; // in pixels
  25483. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25484. Scene.LongPressDelay = 500; // in milliseconds
  25485. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25486. Scene.DoubleClickDelay = 300; // in milliseconds
  25487. /** If you need to check double click without raising a single click at first click, enable this flag */
  25488. Scene.ExclusiveDoubleClickMode = false;
  25489. return Scene;
  25490. }());
  25491. BABYLON.Scene = Scene;
  25492. })(BABYLON || (BABYLON = {}));
  25493. //# sourceMappingURL=babylon.scene.js.map
  25494. var BABYLON;
  25495. (function (BABYLON) {
  25496. /**
  25497. * Set of assets to keep when moving a scene into an asset container.
  25498. */
  25499. var KeepAssets = /** @class */ (function () {
  25500. function KeepAssets() {
  25501. /**
  25502. * Cameras to keep.
  25503. */
  25504. this.cameras = new Array();
  25505. /**
  25506. * Lights to keep.
  25507. */
  25508. this.lights = new Array();
  25509. /**
  25510. * Meshes to keep.
  25511. */
  25512. this.meshes = new Array();
  25513. /**
  25514. * Skeletons to keep.
  25515. */
  25516. this.skeletons = new Array();
  25517. /**
  25518. * ParticleSystems to keep.
  25519. */
  25520. this.particleSystems = new Array();
  25521. /**
  25522. * Animations to keep.
  25523. */
  25524. this.animations = new Array();
  25525. /**
  25526. * MultiMaterials to keep.
  25527. */
  25528. this.multiMaterials = new Array();
  25529. /**
  25530. * Materials to keep.
  25531. */
  25532. this.materials = new Array();
  25533. /**
  25534. * MorphTargetManagers to keep.
  25535. */
  25536. this.morphTargetManagers = new Array();
  25537. /**
  25538. * Geometries to keep.
  25539. */
  25540. this.geometries = new Array();
  25541. /**
  25542. * TransformNodes to keep.
  25543. */
  25544. this.transformNodes = new Array();
  25545. /**
  25546. * LensFlareSystems to keep.
  25547. */
  25548. this.lensFlareSystems = new Array();
  25549. /**
  25550. * ShadowGenerators to keep.
  25551. */
  25552. this.shadowGenerators = new Array();
  25553. /**
  25554. * ActionManagers to keep.
  25555. */
  25556. this.actionManagers = new Array();
  25557. /**
  25558. * Sounds to keep.
  25559. */
  25560. this.sounds = new Array();
  25561. }
  25562. return KeepAssets;
  25563. }());
  25564. BABYLON.KeepAssets = KeepAssets;
  25565. /**
  25566. * Container with a set of assets that can be added or removed from a scene.
  25567. */
  25568. var AssetContainer = /** @class */ (function () {
  25569. /**
  25570. * Instantiates an AssetContainer.
  25571. * @param scene The scene the AssetContainer belongs to.
  25572. */
  25573. function AssetContainer(scene) {
  25574. // Objects
  25575. /**
  25576. * Cameras populated in the container.
  25577. */
  25578. this.cameras = new Array();
  25579. /**
  25580. * Lights populated in the container.
  25581. */
  25582. this.lights = new Array();
  25583. /**
  25584. * Meshes populated in the container.
  25585. */
  25586. this.meshes = new Array();
  25587. /**
  25588. * Skeletons populated in the container.
  25589. */
  25590. this.skeletons = new Array();
  25591. /**
  25592. * ParticleSystems populated in the container.
  25593. */
  25594. this.particleSystems = new Array();
  25595. /**
  25596. * Animations populated in the container.
  25597. */
  25598. this.animations = new Array();
  25599. /**
  25600. * MultiMaterials populated in the container.
  25601. */
  25602. this.multiMaterials = new Array();
  25603. /**
  25604. * Materials populated in the container.
  25605. */
  25606. this.materials = new Array();
  25607. /**
  25608. * MorphTargetManagers populated in the container.
  25609. */
  25610. this.morphTargetManagers = new Array();
  25611. /**
  25612. * Geometries populated in the container.
  25613. */
  25614. this.geometries = new Array();
  25615. /**
  25616. * TransformNodes populated in the container.
  25617. */
  25618. this.transformNodes = new Array();
  25619. /**
  25620. * LensFlareSystems populated in the container.
  25621. */
  25622. this.lensFlareSystems = new Array();
  25623. /**
  25624. * ShadowGenerators populated in the container.
  25625. */
  25626. this.shadowGenerators = new Array();
  25627. /**
  25628. * ActionManagers populated in the container.
  25629. */
  25630. this.actionManagers = new Array();
  25631. /**
  25632. * Sounds populated in the container.
  25633. */
  25634. this.sounds = new Array();
  25635. this.scene = scene;
  25636. }
  25637. /**
  25638. * Adds all the assets from the container to the scene.
  25639. */
  25640. AssetContainer.prototype.addAllToScene = function () {
  25641. var _this = this;
  25642. this.cameras.forEach(function (o) {
  25643. _this.scene.addCamera(o);
  25644. });
  25645. this.lights.forEach(function (o) {
  25646. _this.scene.addLight(o);
  25647. });
  25648. this.meshes.forEach(function (o) {
  25649. _this.scene.addMesh(o);
  25650. });
  25651. this.skeletons.forEach(function (o) {
  25652. _this.scene.addSkeleton(o);
  25653. });
  25654. this.particleSystems.forEach(function (o) {
  25655. _this.scene.addParticleSystem(o);
  25656. });
  25657. this.animations.forEach(function (o) {
  25658. _this.scene.addAnimation(o);
  25659. });
  25660. this.multiMaterials.forEach(function (o) {
  25661. _this.scene.addMultiMaterial(o);
  25662. });
  25663. this.materials.forEach(function (o) {
  25664. _this.scene.addMaterial(o);
  25665. });
  25666. this.morphTargetManagers.forEach(function (o) {
  25667. _this.scene.addMorphTargetManager(o);
  25668. });
  25669. this.geometries.forEach(function (o) {
  25670. _this.scene.addGeometry(o);
  25671. });
  25672. this.transformNodes.forEach(function (o) {
  25673. _this.scene.addTransformNode(o);
  25674. });
  25675. this.lensFlareSystems.forEach(function (o) {
  25676. _this.scene.addLensFlareSystem(o);
  25677. });
  25678. this.actionManagers.forEach(function (o) {
  25679. _this.scene.addActionManager(o);
  25680. });
  25681. this.sounds.forEach(function (o) {
  25682. o.play();
  25683. o.autoplay = true;
  25684. _this.scene.mainSoundTrack.AddSound(o);
  25685. });
  25686. };
  25687. /**
  25688. * Removes all the assets in the container from the scene
  25689. */
  25690. AssetContainer.prototype.removeAllFromScene = function () {
  25691. var _this = this;
  25692. this.cameras.forEach(function (o) {
  25693. _this.scene.removeCamera(o);
  25694. });
  25695. this.lights.forEach(function (o) {
  25696. _this.scene.removeLight(o);
  25697. });
  25698. this.meshes.forEach(function (o) {
  25699. _this.scene.removeMesh(o);
  25700. });
  25701. this.skeletons.forEach(function (o) {
  25702. _this.scene.removeSkeleton(o);
  25703. });
  25704. this.particleSystems.forEach(function (o) {
  25705. _this.scene.removeParticleSystem(o);
  25706. });
  25707. this.animations.forEach(function (o) {
  25708. _this.scene.removeAnimation(o);
  25709. });
  25710. this.multiMaterials.forEach(function (o) {
  25711. _this.scene.removeMultiMaterial(o);
  25712. });
  25713. this.materials.forEach(function (o) {
  25714. _this.scene.removeMaterial(o);
  25715. });
  25716. this.morphTargetManagers.forEach(function (o) {
  25717. _this.scene.removeMorphTargetManager(o);
  25718. });
  25719. this.geometries.forEach(function (o) {
  25720. _this.scene.removeGeometry(o);
  25721. });
  25722. this.transformNodes.forEach(function (o) {
  25723. _this.scene.removeTransformNode(o);
  25724. });
  25725. this.lensFlareSystems.forEach(function (o) {
  25726. _this.scene.removeLensFlareSystem(o);
  25727. });
  25728. this.actionManagers.forEach(function (o) {
  25729. _this.scene.removeActionManager(o);
  25730. });
  25731. this.sounds.forEach(function (o) {
  25732. o.stop();
  25733. o.autoplay = false;
  25734. _this.scene.mainSoundTrack.RemoveSound(o);
  25735. });
  25736. };
  25737. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25738. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25739. var asset = sourceAssets_1[_i];
  25740. var move = true;
  25741. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25742. var keepAsset = keepAssets_1[_a];
  25743. if (asset === keepAsset) {
  25744. move = false;
  25745. break;
  25746. }
  25747. }
  25748. if (move) {
  25749. targetAssets.push(asset);
  25750. }
  25751. }
  25752. };
  25753. /**
  25754. * Removes all the assets contained in the scene and adds them to the container.
  25755. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25756. */
  25757. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25758. if (keepAssets === undefined) {
  25759. keepAssets = new KeepAssets();
  25760. }
  25761. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25762. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25763. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25764. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25765. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25766. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25767. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25768. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25769. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25770. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25771. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25772. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25773. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25774. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25775. this.removeAllFromScene();
  25776. };
  25777. return AssetContainer;
  25778. }());
  25779. BABYLON.AssetContainer = AssetContainer;
  25780. })(BABYLON || (BABYLON = {}));
  25781. //# sourceMappingURL=babylon.assetContainer.js.map
  25782. var BABYLON;
  25783. (function (BABYLON) {
  25784. var Buffer = /** @class */ (function () {
  25785. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25786. if (instanced === void 0) { instanced = false; }
  25787. if (engine instanceof BABYLON.Mesh) {
  25788. this._engine = engine.getScene().getEngine();
  25789. }
  25790. else {
  25791. this._engine = engine;
  25792. }
  25793. this._updatable = updatable;
  25794. this._instanced = instanced;
  25795. this._data = data;
  25796. this._strideSize = stride;
  25797. if (!postponeInternalCreation) {
  25798. this.create();
  25799. }
  25800. }
  25801. /**
  25802. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25803. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25804. * @param offset defines offset in the buffer (0 by default)
  25805. * @param size defines the size in floats of attributes (position is 3 for instance)
  25806. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25807. * @param instanced defines if the vertex buffer contains indexed data
  25808. * @returns the new vertex buffer
  25809. */
  25810. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25811. // a lot of these parameters are ignored as they are overriden by the buffer
  25812. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25813. };
  25814. // Properties
  25815. Buffer.prototype.isUpdatable = function () {
  25816. return this._updatable;
  25817. };
  25818. Buffer.prototype.getData = function () {
  25819. return this._data;
  25820. };
  25821. Buffer.prototype.getBuffer = function () {
  25822. return this._buffer;
  25823. };
  25824. Buffer.prototype.getStrideSize = function () {
  25825. return this._strideSize;
  25826. };
  25827. // public getIsInstanced(): boolean {
  25828. // return this._instanced;
  25829. // }
  25830. // public get instanceDivisor(): number {
  25831. // return this._instanceDivisor;
  25832. // }
  25833. // public set instanceDivisor(value: number) {
  25834. // this._instanceDivisor = value;
  25835. // if (value == 0) {
  25836. // this._instanced = false;
  25837. // } else {
  25838. // this._instanced = true;
  25839. // }
  25840. // }
  25841. // Methods
  25842. Buffer.prototype.create = function (data) {
  25843. if (data === void 0) { data = null; }
  25844. if (!data && this._buffer) {
  25845. return; // nothing to do
  25846. }
  25847. data = data || this._data;
  25848. if (!data) {
  25849. return;
  25850. }
  25851. if (!this._buffer) {
  25852. if (this._updatable) {
  25853. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25854. this._data = data;
  25855. }
  25856. else {
  25857. this._buffer = this._engine.createVertexBuffer(data);
  25858. }
  25859. }
  25860. else if (this._updatable) {
  25861. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25862. this._data = data;
  25863. }
  25864. };
  25865. Buffer.prototype._rebuild = function () {
  25866. this._buffer = null;
  25867. this.create(this._data);
  25868. };
  25869. Buffer.prototype.update = function (data) {
  25870. this.create(data);
  25871. };
  25872. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25873. if (!this._buffer) {
  25874. return;
  25875. }
  25876. if (this._updatable) {
  25877. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25878. this._data = null;
  25879. }
  25880. };
  25881. Buffer.prototype.dispose = function () {
  25882. if (!this._buffer) {
  25883. return;
  25884. }
  25885. if (this._engine._releaseBuffer(this._buffer)) {
  25886. this._buffer = null;
  25887. }
  25888. };
  25889. return Buffer;
  25890. }());
  25891. BABYLON.Buffer = Buffer;
  25892. })(BABYLON || (BABYLON = {}));
  25893. //# sourceMappingURL=babylon.buffer.js.map
  25894. var BABYLON;
  25895. (function (BABYLON) {
  25896. var VertexBuffer = /** @class */ (function () {
  25897. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25898. if (data instanceof BABYLON.Buffer) {
  25899. if (!stride) {
  25900. stride = data.getStrideSize();
  25901. }
  25902. this._buffer = data;
  25903. this._ownsBuffer = false;
  25904. }
  25905. else {
  25906. if (!stride) {
  25907. stride = VertexBuffer.DeduceStride(kind);
  25908. }
  25909. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25910. this._ownsBuffer = true;
  25911. }
  25912. this._stride = stride;
  25913. this._instanced = instanced !== undefined ? instanced : false;
  25914. this._instanceDivisor = instanced ? 1 : 0;
  25915. this._offset = offset ? offset : 0;
  25916. this._size = size ? size : stride;
  25917. this._kind = kind;
  25918. }
  25919. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25920. /**
  25921. * Gets or sets the instance divisor when in instanced mode
  25922. */
  25923. get: function () {
  25924. return this._instanceDivisor;
  25925. },
  25926. set: function (value) {
  25927. this._instanceDivisor = value;
  25928. if (value == 0) {
  25929. this._instanced = false;
  25930. }
  25931. else {
  25932. this._instanced = true;
  25933. }
  25934. },
  25935. enumerable: true,
  25936. configurable: true
  25937. });
  25938. VertexBuffer.prototype._rebuild = function () {
  25939. if (!this._buffer) {
  25940. return;
  25941. }
  25942. this._buffer._rebuild();
  25943. };
  25944. /**
  25945. * Returns the kind of the VertexBuffer (string).
  25946. */
  25947. VertexBuffer.prototype.getKind = function () {
  25948. return this._kind;
  25949. };
  25950. // Properties
  25951. /**
  25952. * Boolean : is the VertexBuffer updatable ?
  25953. */
  25954. VertexBuffer.prototype.isUpdatable = function () {
  25955. return this._buffer.isUpdatable();
  25956. };
  25957. /**
  25958. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25959. */
  25960. VertexBuffer.prototype.getData = function () {
  25961. return this._buffer.getData();
  25962. };
  25963. /**
  25964. * Returns the WebGLBuffer associated to the VertexBuffer.
  25965. */
  25966. VertexBuffer.prototype.getBuffer = function () {
  25967. return this._buffer.getBuffer();
  25968. };
  25969. /**
  25970. * Returns the stride of the VertexBuffer (integer).
  25971. */
  25972. VertexBuffer.prototype.getStrideSize = function () {
  25973. return this._stride;
  25974. };
  25975. /**
  25976. * Returns the offset (integer).
  25977. */
  25978. VertexBuffer.prototype.getOffset = function () {
  25979. return this._offset;
  25980. };
  25981. /**
  25982. * Returns the VertexBuffer total size (integer).
  25983. */
  25984. VertexBuffer.prototype.getSize = function () {
  25985. return this._size;
  25986. };
  25987. /**
  25988. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25989. */
  25990. VertexBuffer.prototype.getIsInstanced = function () {
  25991. return this._instanced;
  25992. };
  25993. /**
  25994. * Returns the instancing divisor, zero for non-instanced (integer).
  25995. */
  25996. VertexBuffer.prototype.getInstanceDivisor = function () {
  25997. return this._instanceDivisor;
  25998. };
  25999. // Methods
  26000. /**
  26001. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26002. * Returns the created WebGLBuffer.
  26003. */
  26004. VertexBuffer.prototype.create = function (data) {
  26005. return this._buffer.create(data);
  26006. };
  26007. /**
  26008. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26009. * This function will create a new buffer if the current one is not updatable
  26010. * Returns the updated WebGLBuffer.
  26011. */
  26012. VertexBuffer.prototype.update = function (data) {
  26013. return this._buffer.update(data);
  26014. };
  26015. /**
  26016. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26017. * Returns the directly updated WebGLBuffer.
  26018. */
  26019. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26020. return this._buffer.updateDirectly(data, offset);
  26021. };
  26022. /**
  26023. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26024. */
  26025. VertexBuffer.prototype.dispose = function () {
  26026. if (this._ownsBuffer) {
  26027. this._buffer.dispose();
  26028. }
  26029. };
  26030. Object.defineProperty(VertexBuffer, "PositionKind", {
  26031. get: function () {
  26032. return VertexBuffer._PositionKind;
  26033. },
  26034. enumerable: true,
  26035. configurable: true
  26036. });
  26037. Object.defineProperty(VertexBuffer, "NormalKind", {
  26038. get: function () {
  26039. return VertexBuffer._NormalKind;
  26040. },
  26041. enumerable: true,
  26042. configurable: true
  26043. });
  26044. Object.defineProperty(VertexBuffer, "TangentKind", {
  26045. get: function () {
  26046. return VertexBuffer._TangentKind;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. Object.defineProperty(VertexBuffer, "UVKind", {
  26052. get: function () {
  26053. return VertexBuffer._UVKind;
  26054. },
  26055. enumerable: true,
  26056. configurable: true
  26057. });
  26058. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26059. get: function () {
  26060. return VertexBuffer._UV2Kind;
  26061. },
  26062. enumerable: true,
  26063. configurable: true
  26064. });
  26065. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26066. get: function () {
  26067. return VertexBuffer._UV3Kind;
  26068. },
  26069. enumerable: true,
  26070. configurable: true
  26071. });
  26072. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26073. get: function () {
  26074. return VertexBuffer._UV4Kind;
  26075. },
  26076. enumerable: true,
  26077. configurable: true
  26078. });
  26079. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26080. get: function () {
  26081. return VertexBuffer._UV5Kind;
  26082. },
  26083. enumerable: true,
  26084. configurable: true
  26085. });
  26086. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26087. get: function () {
  26088. return VertexBuffer._UV6Kind;
  26089. },
  26090. enumerable: true,
  26091. configurable: true
  26092. });
  26093. Object.defineProperty(VertexBuffer, "ColorKind", {
  26094. get: function () {
  26095. return VertexBuffer._ColorKind;
  26096. },
  26097. enumerable: true,
  26098. configurable: true
  26099. });
  26100. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26101. get: function () {
  26102. return VertexBuffer._MatricesIndicesKind;
  26103. },
  26104. enumerable: true,
  26105. configurable: true
  26106. });
  26107. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26108. get: function () {
  26109. return VertexBuffer._MatricesWeightsKind;
  26110. },
  26111. enumerable: true,
  26112. configurable: true
  26113. });
  26114. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26115. get: function () {
  26116. return VertexBuffer._MatricesIndicesExtraKind;
  26117. },
  26118. enumerable: true,
  26119. configurable: true
  26120. });
  26121. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26122. get: function () {
  26123. return VertexBuffer._MatricesWeightsExtraKind;
  26124. },
  26125. enumerable: true,
  26126. configurable: true
  26127. });
  26128. /**
  26129. * Deduces the stride given a kind.
  26130. * @param kind The kind string to deduce
  26131. * @returns The deduced stride
  26132. */
  26133. VertexBuffer.DeduceStride = function (kind) {
  26134. switch (kind) {
  26135. case VertexBuffer.UVKind:
  26136. case VertexBuffer.UV2Kind:
  26137. case VertexBuffer.UV3Kind:
  26138. case VertexBuffer.UV4Kind:
  26139. case VertexBuffer.UV5Kind:
  26140. case VertexBuffer.UV6Kind:
  26141. return 2;
  26142. case VertexBuffer.NormalKind:
  26143. case VertexBuffer.PositionKind:
  26144. return 3;
  26145. case VertexBuffer.ColorKind:
  26146. case VertexBuffer.MatricesIndicesKind:
  26147. case VertexBuffer.MatricesIndicesExtraKind:
  26148. case VertexBuffer.MatricesWeightsKind:
  26149. case VertexBuffer.MatricesWeightsExtraKind:
  26150. case VertexBuffer.TangentKind:
  26151. return 4;
  26152. default:
  26153. throw new Error("Invalid kind '" + kind + "'");
  26154. }
  26155. };
  26156. // Enums
  26157. VertexBuffer._PositionKind = "position";
  26158. VertexBuffer._NormalKind = "normal";
  26159. VertexBuffer._TangentKind = "tangent";
  26160. VertexBuffer._UVKind = "uv";
  26161. VertexBuffer._UV2Kind = "uv2";
  26162. VertexBuffer._UV3Kind = "uv3";
  26163. VertexBuffer._UV4Kind = "uv4";
  26164. VertexBuffer._UV5Kind = "uv5";
  26165. VertexBuffer._UV6Kind = "uv6";
  26166. VertexBuffer._ColorKind = "color";
  26167. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26168. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26169. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26170. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26171. return VertexBuffer;
  26172. }());
  26173. BABYLON.VertexBuffer = VertexBuffer;
  26174. })(BABYLON || (BABYLON = {}));
  26175. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26176. var BABYLON;
  26177. (function (BABYLON) {
  26178. /**
  26179. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26180. */
  26181. var DummyInternalTextureTracker = /** @class */ (function () {
  26182. function DummyInternalTextureTracker() {
  26183. /**
  26184. * Gets or set the previous tracker in the list
  26185. */
  26186. this.previous = null;
  26187. /**
  26188. * Gets or set the next tracker in the list
  26189. */
  26190. this.next = null;
  26191. }
  26192. return DummyInternalTextureTracker;
  26193. }());
  26194. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26195. })(BABYLON || (BABYLON = {}));
  26196. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26197. var BABYLON;
  26198. (function (BABYLON) {
  26199. /**
  26200. * Class used to store data associated with WebGL texture data for the engine
  26201. * This class should not be used directly
  26202. */
  26203. var InternalTexture = /** @class */ (function () {
  26204. /**
  26205. * Creates a new InternalTexture
  26206. * @param engine defines the engine to use
  26207. * @param dataSource defines the type of data that will be used
  26208. */
  26209. function InternalTexture(engine, dataSource) {
  26210. /**
  26211. * Observable called when the texture is loaded
  26212. */
  26213. this.onLoadedObservable = new BABYLON.Observable();
  26214. /**
  26215. * Gets or set the previous tracker in the list
  26216. */
  26217. this.previous = null;
  26218. /**
  26219. * Gets or set the next tracker in the list
  26220. */
  26221. this.next = null;
  26222. // Private
  26223. /** @ignore */
  26224. this._initialSlot = -1;
  26225. /** @ignore */
  26226. this._designatedSlot = -1;
  26227. /** @ignore */
  26228. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26229. /** @ignore */
  26230. this._comparisonFunction = 0;
  26231. /** @ignore */
  26232. this._references = 1;
  26233. this._engine = engine;
  26234. this._dataSource = dataSource;
  26235. this._webGLTexture = engine._createTexture();
  26236. }
  26237. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26238. /**
  26239. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26240. */
  26241. get: function () {
  26242. return this._dataSource;
  26243. },
  26244. enumerable: true,
  26245. configurable: true
  26246. });
  26247. /**
  26248. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26249. */
  26250. InternalTexture.prototype.incrementReferences = function () {
  26251. this._references++;
  26252. };
  26253. /**
  26254. * Change the size of the texture (not the size of the content)
  26255. * @param width defines the new width
  26256. * @param height defines the new height
  26257. * @param depth defines the new depth (1 by default)
  26258. */
  26259. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26260. if (depth === void 0) { depth = 1; }
  26261. this.width = width;
  26262. this.height = height;
  26263. this.depth = depth;
  26264. this.baseWidth = width;
  26265. this.baseHeight = height;
  26266. this.baseDepth = depth;
  26267. this._size = width * height * depth;
  26268. };
  26269. /** @ignore */
  26270. InternalTexture.prototype._rebuild = function () {
  26271. var _this = this;
  26272. var proxy;
  26273. this.isReady = false;
  26274. this._cachedCoordinatesMode = null;
  26275. this._cachedWrapU = null;
  26276. this._cachedWrapV = null;
  26277. this._cachedAnisotropicFilteringLevel = null;
  26278. switch (this._dataSource) {
  26279. case InternalTexture.DATASOURCE_TEMP:
  26280. return;
  26281. case InternalTexture.DATASOURCE_URL:
  26282. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26283. _this.isReady = true;
  26284. }, null, this._buffer, undefined, this.format);
  26285. proxy._swapAndDie(this);
  26286. return;
  26287. case InternalTexture.DATASOURCE_RAW:
  26288. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26289. proxy._swapAndDie(this);
  26290. this.isReady = true;
  26291. return;
  26292. case InternalTexture.DATASOURCE_RAW3D:
  26293. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26294. proxy._swapAndDie(this);
  26295. this.isReady = true;
  26296. return;
  26297. case InternalTexture.DATASOURCE_DYNAMIC:
  26298. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26299. proxy._swapAndDie(this);
  26300. // The engine will make sure to update content so no need to flag it as isReady = true
  26301. return;
  26302. case InternalTexture.DATASOURCE_RENDERTARGET:
  26303. var options = new BABYLON.RenderTargetCreationOptions();
  26304. options.generateDepthBuffer = this._generateDepthBuffer;
  26305. options.generateMipMaps = this.generateMipMaps;
  26306. options.generateStencilBuffer = this._generateStencilBuffer;
  26307. options.samplingMode = this.samplingMode;
  26308. options.type = this.type;
  26309. if (this.isCube) {
  26310. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26311. }
  26312. else {
  26313. var size = {
  26314. width: this.width,
  26315. height: this.height
  26316. };
  26317. proxy = this._engine.createRenderTargetTexture(size, options);
  26318. }
  26319. proxy._swapAndDie(this);
  26320. this.isReady = true;
  26321. return;
  26322. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26323. var depthTextureOptions = {
  26324. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26325. comparisonFunction: this._comparisonFunction,
  26326. generateStencil: this._generateStencilBuffer,
  26327. };
  26328. if (this.isCube) {
  26329. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26330. }
  26331. else {
  26332. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26333. }
  26334. proxy._swapAndDie(this);
  26335. this.isReady = true;
  26336. return;
  26337. case InternalTexture.DATASOURCE_CUBE:
  26338. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26339. _this.isReady = true;
  26340. }, null, this.format, this._extension);
  26341. proxy._swapAndDie(this);
  26342. return;
  26343. case InternalTexture.DATASOURCE_CUBERAW:
  26344. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26345. proxy._swapAndDie(this);
  26346. this.isReady = true;
  26347. return;
  26348. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26349. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26350. if (proxy) {
  26351. proxy._swapAndDie(_this);
  26352. }
  26353. _this.isReady = true;
  26354. }, null, this.format, this._extension);
  26355. return;
  26356. }
  26357. };
  26358. InternalTexture.prototype._swapAndDie = function (target) {
  26359. target._webGLTexture = this._webGLTexture;
  26360. if (this._framebuffer) {
  26361. target._framebuffer = this._framebuffer;
  26362. }
  26363. if (this._depthStencilBuffer) {
  26364. target._depthStencilBuffer = this._depthStencilBuffer;
  26365. }
  26366. if (this._lodTextureHigh) {
  26367. if (target._lodTextureHigh) {
  26368. target._lodTextureHigh.dispose();
  26369. }
  26370. target._lodTextureHigh = this._lodTextureHigh;
  26371. }
  26372. if (this._lodTextureMid) {
  26373. if (target._lodTextureMid) {
  26374. target._lodTextureMid.dispose();
  26375. }
  26376. target._lodTextureMid = this._lodTextureMid;
  26377. }
  26378. if (this._lodTextureLow) {
  26379. if (target._lodTextureLow) {
  26380. target._lodTextureLow.dispose();
  26381. }
  26382. target._lodTextureLow = this._lodTextureLow;
  26383. }
  26384. var cache = this._engine.getLoadedTexturesCache();
  26385. var index = cache.indexOf(this);
  26386. if (index !== -1) {
  26387. cache.splice(index, 1);
  26388. }
  26389. };
  26390. /**
  26391. * Dispose the current allocated resources
  26392. */
  26393. InternalTexture.prototype.dispose = function () {
  26394. if (!this._webGLTexture) {
  26395. return;
  26396. }
  26397. this._references--;
  26398. if (this._references === 0) {
  26399. this._engine._releaseTexture(this);
  26400. this._webGLTexture = null;
  26401. this.previous = null;
  26402. this.next = null;
  26403. }
  26404. };
  26405. /**
  26406. * The source of the texture data is unknown
  26407. */
  26408. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26409. /**
  26410. * Texture data comes from an URL
  26411. */
  26412. InternalTexture.DATASOURCE_URL = 1;
  26413. /**
  26414. * Texture data is only used for temporary storage
  26415. */
  26416. InternalTexture.DATASOURCE_TEMP = 2;
  26417. /**
  26418. * Texture data comes from raw data (ArrayBuffer)
  26419. */
  26420. InternalTexture.DATASOURCE_RAW = 3;
  26421. /**
  26422. * Texture content is dynamic (video or dynamic texture)
  26423. */
  26424. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26425. /**
  26426. * Texture content is generated by rendering to it
  26427. */
  26428. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26429. /**
  26430. * Texture content is part of a multi render target process
  26431. */
  26432. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26433. /**
  26434. * Texture data comes from a cube data file
  26435. */
  26436. InternalTexture.DATASOURCE_CUBE = 7;
  26437. /**
  26438. * Texture data comes from a raw cube data
  26439. */
  26440. InternalTexture.DATASOURCE_CUBERAW = 8;
  26441. /**
  26442. * Texture data come from a prefiltered cube data file
  26443. */
  26444. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26445. /**
  26446. * Texture content is raw 3D data
  26447. */
  26448. InternalTexture.DATASOURCE_RAW3D = 10;
  26449. /**
  26450. * Texture content is a depth texture
  26451. */
  26452. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26453. return InternalTexture;
  26454. }());
  26455. BABYLON.InternalTexture = InternalTexture;
  26456. })(BABYLON || (BABYLON = {}));
  26457. //# sourceMappingURL=babylon.internalTexture.js.map
  26458. var BABYLON;
  26459. (function (BABYLON) {
  26460. var BaseTexture = /** @class */ (function () {
  26461. function BaseTexture(scene) {
  26462. this._hasAlpha = false;
  26463. this.getAlphaFromRGB = false;
  26464. this.level = 1;
  26465. this.coordinatesIndex = 0;
  26466. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26467. /**
  26468. * | Value | Type | Description |
  26469. * | ----- | ------------------ | ----------- |
  26470. * | 0 | CLAMP_ADDRESSMODE | |
  26471. * | 1 | WRAP_ADDRESSMODE | |
  26472. * | 2 | MIRROR_ADDRESSMODE | |
  26473. */
  26474. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26475. /**
  26476. * | Value | Type | Description |
  26477. * | ----- | ------------------ | ----------- |
  26478. * | 0 | CLAMP_ADDRESSMODE | |
  26479. * | 1 | WRAP_ADDRESSMODE | |
  26480. * | 2 | MIRROR_ADDRESSMODE | |
  26481. */
  26482. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26483. /**
  26484. * | Value | Type | Description |
  26485. * | ----- | ------------------ | ----------- |
  26486. * | 0 | CLAMP_ADDRESSMODE | |
  26487. * | 1 | WRAP_ADDRESSMODE | |
  26488. * | 2 | MIRROR_ADDRESSMODE | |
  26489. */
  26490. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26491. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26492. this.isCube = false;
  26493. this.is3D = false;
  26494. this.gammaSpace = true;
  26495. this.invertZ = false;
  26496. this.lodLevelInAlpha = false;
  26497. this.lodGenerationOffset = 0.0;
  26498. this.lodGenerationScale = 0.8;
  26499. this.isRenderTarget = false;
  26500. this.animations = new Array();
  26501. /**
  26502. * An event triggered when the texture is disposed.
  26503. * @type {BABYLON.Observable}
  26504. */
  26505. this.onDisposeObservable = new BABYLON.Observable();
  26506. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26507. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26508. if (this._scene) {
  26509. this._scene.textures.push(this);
  26510. }
  26511. this._uid = null;
  26512. }
  26513. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26514. get: function () {
  26515. return this._hasAlpha;
  26516. },
  26517. set: function (value) {
  26518. if (this._hasAlpha === value) {
  26519. return;
  26520. }
  26521. this._hasAlpha = value;
  26522. if (this._scene) {
  26523. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26524. }
  26525. },
  26526. enumerable: true,
  26527. configurable: true
  26528. });
  26529. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26530. get: function () {
  26531. return this._coordinatesMode;
  26532. },
  26533. /**
  26534. * How a texture is mapped.
  26535. *
  26536. * | Value | Type | Description |
  26537. * | ----- | ----------------------------------- | ----------- |
  26538. * | 0 | EXPLICIT_MODE | |
  26539. * | 1 | SPHERICAL_MODE | |
  26540. * | 2 | PLANAR_MODE | |
  26541. * | 3 | CUBIC_MODE | |
  26542. * | 4 | PROJECTION_MODE | |
  26543. * | 5 | SKYBOX_MODE | |
  26544. * | 6 | INVCUBIC_MODE | |
  26545. * | 7 | EQUIRECTANGULAR_MODE | |
  26546. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26547. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26548. */
  26549. set: function (value) {
  26550. if (this._coordinatesMode === value) {
  26551. return;
  26552. }
  26553. this._coordinatesMode = value;
  26554. if (this._scene) {
  26555. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26556. }
  26557. },
  26558. enumerable: true,
  26559. configurable: true
  26560. });
  26561. Object.defineProperty(BaseTexture.prototype, "uid", {
  26562. get: function () {
  26563. if (!this._uid) {
  26564. this._uid = BABYLON.Tools.RandomId();
  26565. }
  26566. return this._uid;
  26567. },
  26568. enumerable: true,
  26569. configurable: true
  26570. });
  26571. BaseTexture.prototype.toString = function () {
  26572. return this.name;
  26573. };
  26574. BaseTexture.prototype.getClassName = function () {
  26575. return "BaseTexture";
  26576. };
  26577. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26578. set: function (callback) {
  26579. if (this._onDisposeObserver) {
  26580. this.onDisposeObservable.remove(this._onDisposeObserver);
  26581. }
  26582. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26583. },
  26584. enumerable: true,
  26585. configurable: true
  26586. });
  26587. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26588. get: function () {
  26589. return true;
  26590. },
  26591. enumerable: true,
  26592. configurable: true
  26593. });
  26594. BaseTexture.prototype.getScene = function () {
  26595. return this._scene;
  26596. };
  26597. BaseTexture.prototype.getTextureMatrix = function () {
  26598. return BABYLON.Matrix.IdentityReadOnly;
  26599. };
  26600. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26601. return BABYLON.Matrix.IdentityReadOnly;
  26602. };
  26603. BaseTexture.prototype.getInternalTexture = function () {
  26604. return this._texture;
  26605. };
  26606. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26607. return !this.isBlocking || this.isReady();
  26608. };
  26609. BaseTexture.prototype.isReady = function () {
  26610. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26611. this.delayLoad();
  26612. return false;
  26613. }
  26614. if (this._texture) {
  26615. return this._texture.isReady;
  26616. }
  26617. return false;
  26618. };
  26619. BaseTexture.prototype.getSize = function () {
  26620. if (this._texture && this._texture.width) {
  26621. return new BABYLON.Size(this._texture.width, this._texture.height);
  26622. }
  26623. if (this._texture && this._texture._size) {
  26624. return new BABYLON.Size(this._texture._size, this._texture._size);
  26625. }
  26626. return BABYLON.Size.Zero();
  26627. };
  26628. BaseTexture.prototype.getBaseSize = function () {
  26629. if (!this.isReady() || !this._texture)
  26630. return BABYLON.Size.Zero();
  26631. if (this._texture._size) {
  26632. return new BABYLON.Size(this._texture._size, this._texture._size);
  26633. }
  26634. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26635. };
  26636. BaseTexture.prototype.scale = function (ratio) {
  26637. };
  26638. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26639. get: function () {
  26640. return false;
  26641. },
  26642. enumerable: true,
  26643. configurable: true
  26644. });
  26645. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26646. if (!this._scene) {
  26647. return null;
  26648. }
  26649. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26650. for (var index = 0; index < texturesCache.length; index++) {
  26651. var texturesCacheEntry = texturesCache[index];
  26652. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26653. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26654. texturesCacheEntry.incrementReferences();
  26655. return texturesCacheEntry;
  26656. }
  26657. }
  26658. }
  26659. return null;
  26660. };
  26661. BaseTexture.prototype._rebuild = function () {
  26662. };
  26663. BaseTexture.prototype.delayLoad = function () {
  26664. };
  26665. BaseTexture.prototype.clone = function () {
  26666. return null;
  26667. };
  26668. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26669. get: function () {
  26670. if (!this._texture) {
  26671. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26672. }
  26673. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26674. },
  26675. enumerable: true,
  26676. configurable: true
  26677. });
  26678. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26679. get: function () {
  26680. if (!this._texture) {
  26681. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26682. }
  26683. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. BaseTexture.prototype.readPixels = function (faceIndex) {
  26689. if (faceIndex === void 0) { faceIndex = 0; }
  26690. if (!this._texture) {
  26691. return null;
  26692. }
  26693. var size = this.getSize();
  26694. var scene = this.getScene();
  26695. if (!scene) {
  26696. return null;
  26697. }
  26698. var engine = scene.getEngine();
  26699. if (this._texture.isCube) {
  26700. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26701. }
  26702. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26703. };
  26704. BaseTexture.prototype.releaseInternalTexture = function () {
  26705. if (this._texture) {
  26706. this._texture.dispose();
  26707. this._texture = null;
  26708. }
  26709. };
  26710. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26711. get: function () {
  26712. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26713. return null;
  26714. }
  26715. if (!this._texture._sphericalPolynomial) {
  26716. this._texture._sphericalPolynomial =
  26717. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26718. }
  26719. return this._texture._sphericalPolynomial;
  26720. },
  26721. set: function (value) {
  26722. if (this._texture) {
  26723. this._texture._sphericalPolynomial = value;
  26724. }
  26725. },
  26726. enumerable: true,
  26727. configurable: true
  26728. });
  26729. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26730. get: function () {
  26731. if (this._texture) {
  26732. return this._texture._lodTextureHigh;
  26733. }
  26734. return null;
  26735. },
  26736. enumerable: true,
  26737. configurable: true
  26738. });
  26739. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26740. get: function () {
  26741. if (this._texture) {
  26742. return this._texture._lodTextureMid;
  26743. }
  26744. return null;
  26745. },
  26746. enumerable: true,
  26747. configurable: true
  26748. });
  26749. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26750. get: function () {
  26751. if (this._texture) {
  26752. return this._texture._lodTextureLow;
  26753. }
  26754. return null;
  26755. },
  26756. enumerable: true,
  26757. configurable: true
  26758. });
  26759. BaseTexture.prototype.dispose = function () {
  26760. if (!this._scene) {
  26761. return;
  26762. }
  26763. // Animations
  26764. this._scene.stopAnimation(this);
  26765. // Remove from scene
  26766. this._scene._removePendingData(this);
  26767. var index = this._scene.textures.indexOf(this);
  26768. if (index >= 0) {
  26769. this._scene.textures.splice(index, 1);
  26770. }
  26771. if (this._texture === undefined) {
  26772. return;
  26773. }
  26774. // Release
  26775. this.releaseInternalTexture();
  26776. // Callback
  26777. this.onDisposeObservable.notifyObservers(this);
  26778. this.onDisposeObservable.clear();
  26779. };
  26780. BaseTexture.prototype.serialize = function () {
  26781. if (!this.name) {
  26782. return null;
  26783. }
  26784. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26785. // Animations
  26786. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26787. return serializationObject;
  26788. };
  26789. BaseTexture.WhenAllReady = function (textures, callback) {
  26790. var numRemaining = textures.length;
  26791. if (numRemaining === 0) {
  26792. callback();
  26793. return;
  26794. }
  26795. var _loop_1 = function () {
  26796. texture = textures[i];
  26797. if (texture.isReady()) {
  26798. if (--numRemaining === 0) {
  26799. callback();
  26800. }
  26801. }
  26802. else {
  26803. onLoadObservable = texture.onLoadObservable;
  26804. var onLoadCallback_1 = function () {
  26805. onLoadObservable.removeCallback(onLoadCallback_1);
  26806. if (--numRemaining === 0) {
  26807. callback();
  26808. }
  26809. };
  26810. onLoadObservable.add(onLoadCallback_1);
  26811. }
  26812. };
  26813. var texture, onLoadObservable;
  26814. for (var i = 0; i < textures.length; i++) {
  26815. _loop_1();
  26816. }
  26817. };
  26818. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26819. __decorate([
  26820. BABYLON.serialize()
  26821. ], BaseTexture.prototype, "name", void 0);
  26822. __decorate([
  26823. BABYLON.serialize("hasAlpha")
  26824. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26825. __decorate([
  26826. BABYLON.serialize()
  26827. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26828. __decorate([
  26829. BABYLON.serialize()
  26830. ], BaseTexture.prototype, "level", void 0);
  26831. __decorate([
  26832. BABYLON.serialize()
  26833. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26834. __decorate([
  26835. BABYLON.serialize("coordinatesMode")
  26836. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26837. __decorate([
  26838. BABYLON.serialize()
  26839. ], BaseTexture.prototype, "wrapU", void 0);
  26840. __decorate([
  26841. BABYLON.serialize()
  26842. ], BaseTexture.prototype, "wrapV", void 0);
  26843. __decorate([
  26844. BABYLON.serialize()
  26845. ], BaseTexture.prototype, "wrapR", void 0);
  26846. __decorate([
  26847. BABYLON.serialize()
  26848. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26849. __decorate([
  26850. BABYLON.serialize()
  26851. ], BaseTexture.prototype, "isCube", void 0);
  26852. __decorate([
  26853. BABYLON.serialize()
  26854. ], BaseTexture.prototype, "is3D", void 0);
  26855. __decorate([
  26856. BABYLON.serialize()
  26857. ], BaseTexture.prototype, "gammaSpace", void 0);
  26858. __decorate([
  26859. BABYLON.serialize()
  26860. ], BaseTexture.prototype, "invertZ", void 0);
  26861. __decorate([
  26862. BABYLON.serialize()
  26863. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26864. __decorate([
  26865. BABYLON.serialize()
  26866. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26867. __decorate([
  26868. BABYLON.serialize()
  26869. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26870. __decorate([
  26871. BABYLON.serialize()
  26872. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26873. return BaseTexture;
  26874. }());
  26875. BABYLON.BaseTexture = BaseTexture;
  26876. })(BABYLON || (BABYLON = {}));
  26877. //# sourceMappingURL=babylon.baseTexture.js.map
  26878. var BABYLON;
  26879. (function (BABYLON) {
  26880. var Texture = /** @class */ (function (_super) {
  26881. __extends(Texture, _super);
  26882. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26883. if (noMipmap === void 0) { noMipmap = false; }
  26884. if (invertY === void 0) { invertY = true; }
  26885. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26886. if (onLoad === void 0) { onLoad = null; }
  26887. if (onError === void 0) { onError = null; }
  26888. if (buffer === void 0) { buffer = null; }
  26889. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26890. var _this = _super.call(this, scene) || this;
  26891. _this.uOffset = 0;
  26892. _this.vOffset = 0;
  26893. _this.uScale = 1.0;
  26894. _this.vScale = 1.0;
  26895. _this.uAng = 0;
  26896. _this.vAng = 0;
  26897. _this.wAng = 0;
  26898. _this._isBlocking = true;
  26899. _this.name = url || "";
  26900. _this.url = url;
  26901. _this._noMipmap = noMipmap;
  26902. _this._invertY = invertY;
  26903. _this._samplingMode = samplingMode;
  26904. _this._buffer = buffer;
  26905. _this._deleteBuffer = deleteBuffer;
  26906. if (format) {
  26907. _this._format = format;
  26908. }
  26909. scene = _this.getScene();
  26910. if (!scene) {
  26911. return _this;
  26912. }
  26913. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26914. var load = function () {
  26915. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26916. _this.onLoadObservable.notifyObservers(_this);
  26917. }
  26918. if (onLoad) {
  26919. onLoad();
  26920. }
  26921. if (!_this.isBlocking && scene) {
  26922. scene.resetCachedMaterial();
  26923. }
  26924. };
  26925. if (!_this.url) {
  26926. _this._delayedOnLoad = load;
  26927. _this._delayedOnError = onError;
  26928. return _this;
  26929. }
  26930. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26931. if (!_this._texture) {
  26932. if (!scene.useDelayedTextureLoading) {
  26933. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26934. if (deleteBuffer) {
  26935. delete _this._buffer;
  26936. }
  26937. }
  26938. else {
  26939. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26940. _this._delayedOnLoad = load;
  26941. _this._delayedOnError = onError;
  26942. }
  26943. }
  26944. else {
  26945. if (_this._texture.isReady) {
  26946. BABYLON.Tools.SetImmediate(function () { return load(); });
  26947. }
  26948. else {
  26949. _this._texture.onLoadedObservable.add(load);
  26950. }
  26951. }
  26952. return _this;
  26953. }
  26954. Object.defineProperty(Texture.prototype, "noMipmap", {
  26955. get: function () {
  26956. return this._noMipmap;
  26957. },
  26958. enumerable: true,
  26959. configurable: true
  26960. });
  26961. Object.defineProperty(Texture.prototype, "isBlocking", {
  26962. get: function () {
  26963. return this._isBlocking;
  26964. },
  26965. set: function (value) {
  26966. this._isBlocking = value;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. Object.defineProperty(Texture.prototype, "samplingMode", {
  26972. get: function () {
  26973. return this._samplingMode;
  26974. },
  26975. enumerable: true,
  26976. configurable: true
  26977. });
  26978. Texture.prototype.updateURL = function (url) {
  26979. this.url = url;
  26980. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26981. this.delayLoad();
  26982. };
  26983. Texture.prototype.delayLoad = function () {
  26984. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26985. return;
  26986. }
  26987. var scene = this.getScene();
  26988. if (!scene) {
  26989. return;
  26990. }
  26991. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26992. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26993. if (!this._texture) {
  26994. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26995. if (this._deleteBuffer) {
  26996. delete this._buffer;
  26997. }
  26998. }
  26999. else {
  27000. if (this._delayedOnLoad) {
  27001. if (this._texture.isReady) {
  27002. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27003. }
  27004. else {
  27005. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27006. }
  27007. }
  27008. }
  27009. this._delayedOnLoad = null;
  27010. this._delayedOnError = null;
  27011. };
  27012. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27013. if (!this._texture) {
  27014. return;
  27015. }
  27016. var scene = this.getScene();
  27017. if (!scene) {
  27018. return;
  27019. }
  27020. this._samplingMode = samplingMode;
  27021. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27022. };
  27023. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27024. x *= this.uScale;
  27025. y *= this.vScale;
  27026. x -= 0.5 * this.uScale;
  27027. y -= 0.5 * this.vScale;
  27028. z -= 0.5;
  27029. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27030. t.x += 0.5 * this.uScale + this.uOffset;
  27031. t.y += 0.5 * this.vScale + this.vOffset;
  27032. t.z += 0.5;
  27033. };
  27034. Texture.prototype.getTextureMatrix = function () {
  27035. var _this = this;
  27036. if (this.uOffset === this._cachedUOffset &&
  27037. this.vOffset === this._cachedVOffset &&
  27038. this.uScale === this._cachedUScale &&
  27039. this.vScale === this._cachedVScale &&
  27040. this.uAng === this._cachedUAng &&
  27041. this.vAng === this._cachedVAng &&
  27042. this.wAng === this._cachedWAng) {
  27043. return this._cachedTextureMatrix;
  27044. }
  27045. this._cachedUOffset = this.uOffset;
  27046. this._cachedVOffset = this.vOffset;
  27047. this._cachedUScale = this.uScale;
  27048. this._cachedVScale = this.vScale;
  27049. this._cachedUAng = this.uAng;
  27050. this._cachedVAng = this.vAng;
  27051. this._cachedWAng = this.wAng;
  27052. if (!this._cachedTextureMatrix) {
  27053. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27054. this._rowGenerationMatrix = new BABYLON.Matrix();
  27055. this._t0 = BABYLON.Vector3.Zero();
  27056. this._t1 = BABYLON.Vector3.Zero();
  27057. this._t2 = BABYLON.Vector3.Zero();
  27058. }
  27059. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27060. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27061. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27062. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27063. this._t1.subtractInPlace(this._t0);
  27064. this._t2.subtractInPlace(this._t0);
  27065. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27066. this._cachedTextureMatrix.m[0] = this._t1.x;
  27067. this._cachedTextureMatrix.m[1] = this._t1.y;
  27068. this._cachedTextureMatrix.m[2] = this._t1.z;
  27069. this._cachedTextureMatrix.m[4] = this._t2.x;
  27070. this._cachedTextureMatrix.m[5] = this._t2.y;
  27071. this._cachedTextureMatrix.m[6] = this._t2.z;
  27072. this._cachedTextureMatrix.m[8] = this._t0.x;
  27073. this._cachedTextureMatrix.m[9] = this._t0.y;
  27074. this._cachedTextureMatrix.m[10] = this._t0.z;
  27075. var scene = this.getScene();
  27076. if (!scene) {
  27077. return this._cachedTextureMatrix;
  27078. }
  27079. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27080. return mat.hasTexture(_this);
  27081. });
  27082. return this._cachedTextureMatrix;
  27083. };
  27084. Texture.prototype.getReflectionTextureMatrix = function () {
  27085. var _this = this;
  27086. var scene = this.getScene();
  27087. if (!scene) {
  27088. return this._cachedTextureMatrix;
  27089. }
  27090. if (this.uOffset === this._cachedUOffset &&
  27091. this.vOffset === this._cachedVOffset &&
  27092. this.uScale === this._cachedUScale &&
  27093. this.vScale === this._cachedVScale &&
  27094. this.coordinatesMode === this._cachedCoordinatesMode) {
  27095. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27096. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27097. return this._cachedTextureMatrix;
  27098. }
  27099. }
  27100. else {
  27101. return this._cachedTextureMatrix;
  27102. }
  27103. }
  27104. if (!this._cachedTextureMatrix) {
  27105. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27106. }
  27107. if (!this._projectionModeMatrix) {
  27108. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27109. }
  27110. this._cachedUOffset = this.uOffset;
  27111. this._cachedVOffset = this.vOffset;
  27112. this._cachedUScale = this.uScale;
  27113. this._cachedVScale = this.vScale;
  27114. this._cachedCoordinatesMode = this.coordinatesMode;
  27115. switch (this.coordinatesMode) {
  27116. case Texture.PLANAR_MODE:
  27117. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27118. this._cachedTextureMatrix[0] = this.uScale;
  27119. this._cachedTextureMatrix[5] = this.vScale;
  27120. this._cachedTextureMatrix[12] = this.uOffset;
  27121. this._cachedTextureMatrix[13] = this.vOffset;
  27122. break;
  27123. case Texture.PROJECTION_MODE:
  27124. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27125. this._projectionModeMatrix.m[0] = 0.5;
  27126. this._projectionModeMatrix.m[5] = -0.5;
  27127. this._projectionModeMatrix.m[10] = 0.0;
  27128. this._projectionModeMatrix.m[12] = 0.5;
  27129. this._projectionModeMatrix.m[13] = 0.5;
  27130. this._projectionModeMatrix.m[14] = 1.0;
  27131. this._projectionModeMatrix.m[15] = 1.0;
  27132. var projectionMatrix = scene.getProjectionMatrix();
  27133. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27134. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27135. break;
  27136. default:
  27137. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27138. break;
  27139. }
  27140. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27141. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27142. });
  27143. return this._cachedTextureMatrix;
  27144. };
  27145. Texture.prototype.clone = function () {
  27146. var _this = this;
  27147. return BABYLON.SerializationHelper.Clone(function () {
  27148. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27149. }, this);
  27150. };
  27151. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27152. get: function () {
  27153. if (!this._onLoadObservable) {
  27154. this._onLoadObservable = new BABYLON.Observable();
  27155. }
  27156. return this._onLoadObservable;
  27157. },
  27158. enumerable: true,
  27159. configurable: true
  27160. });
  27161. Texture.prototype.serialize = function () {
  27162. var serializationObject = _super.prototype.serialize.call(this);
  27163. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27164. serializationObject.base64String = this._buffer;
  27165. serializationObject.name = serializationObject.name.replace("data:", "");
  27166. }
  27167. return serializationObject;
  27168. };
  27169. Texture.prototype.getClassName = function () {
  27170. return "Texture";
  27171. };
  27172. Texture.prototype.dispose = function () {
  27173. _super.prototype.dispose.call(this);
  27174. if (this.onLoadObservable) {
  27175. this.onLoadObservable.clear();
  27176. this._onLoadObservable = null;
  27177. }
  27178. this._delayedOnLoad = null;
  27179. this._delayedOnError = null;
  27180. };
  27181. // Statics
  27182. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27183. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27184. if (onLoad === void 0) { onLoad = null; }
  27185. if (onError === void 0) { onError = null; }
  27186. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27187. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27188. };
  27189. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27190. if (parsedTexture.customType) {
  27191. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27192. // Update Sampling Mode
  27193. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27194. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27195. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27196. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27197. }
  27198. }
  27199. return parsedCustomTexture;
  27200. }
  27201. if (parsedTexture.isCube) {
  27202. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27203. }
  27204. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27205. return null;
  27206. }
  27207. var texture = BABYLON.SerializationHelper.Parse(function () {
  27208. var generateMipMaps = true;
  27209. if (parsedTexture.noMipmap) {
  27210. generateMipMaps = false;
  27211. }
  27212. if (parsedTexture.mirrorPlane) {
  27213. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27214. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27215. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27216. return mirrorTexture;
  27217. }
  27218. else if (parsedTexture.isRenderTarget) {
  27219. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27220. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27221. return renderTargetTexture;
  27222. }
  27223. else {
  27224. var texture;
  27225. if (parsedTexture.base64String) {
  27226. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27227. }
  27228. else {
  27229. var url = rootUrl + parsedTexture.name;
  27230. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27231. url = parsedTexture.url;
  27232. }
  27233. texture = new Texture(url, scene, !generateMipMaps);
  27234. }
  27235. return texture;
  27236. }
  27237. }, parsedTexture, scene);
  27238. // Update Sampling Mode
  27239. if (parsedTexture.samplingMode) {
  27240. var sampling = parsedTexture.samplingMode;
  27241. if (texture._samplingMode !== sampling) {
  27242. texture.updateSamplingMode(sampling);
  27243. }
  27244. }
  27245. // Animations
  27246. if (parsedTexture.animations) {
  27247. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27248. var parsedAnimation = parsedTexture.animations[animationIndex];
  27249. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27250. }
  27251. }
  27252. return texture;
  27253. };
  27254. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27255. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27256. if (noMipmap === void 0) { noMipmap = false; }
  27257. if (invertY === void 0) { invertY = true; }
  27258. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27259. if (onLoad === void 0) { onLoad = null; }
  27260. if (onError === void 0) { onError = null; }
  27261. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27262. if (name.substr(0, 5) !== "data:") {
  27263. name = "data:" + name;
  27264. }
  27265. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27266. };
  27267. // Constants
  27268. Texture.NEAREST_SAMPLINGMODE = 1;
  27269. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27270. Texture.BILINEAR_SAMPLINGMODE = 2;
  27271. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27272. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27273. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27274. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27275. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27276. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27277. Texture.NEAREST_LINEAR = 7;
  27278. Texture.NEAREST_NEAREST = 8;
  27279. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27280. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27281. Texture.LINEAR_LINEAR = 11;
  27282. Texture.LINEAR_NEAREST = 12;
  27283. Texture.EXPLICIT_MODE = 0;
  27284. Texture.SPHERICAL_MODE = 1;
  27285. Texture.PLANAR_MODE = 2;
  27286. Texture.CUBIC_MODE = 3;
  27287. Texture.PROJECTION_MODE = 4;
  27288. Texture.SKYBOX_MODE = 5;
  27289. Texture.INVCUBIC_MODE = 6;
  27290. Texture.EQUIRECTANGULAR_MODE = 7;
  27291. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27292. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27293. Texture.CLAMP_ADDRESSMODE = 0;
  27294. Texture.WRAP_ADDRESSMODE = 1;
  27295. Texture.MIRROR_ADDRESSMODE = 2;
  27296. /**
  27297. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27298. */
  27299. Texture.UseSerializedUrlIfAny = false;
  27300. __decorate([
  27301. BABYLON.serialize()
  27302. ], Texture.prototype, "url", void 0);
  27303. __decorate([
  27304. BABYLON.serialize()
  27305. ], Texture.prototype, "uOffset", void 0);
  27306. __decorate([
  27307. BABYLON.serialize()
  27308. ], Texture.prototype, "vOffset", void 0);
  27309. __decorate([
  27310. BABYLON.serialize()
  27311. ], Texture.prototype, "uScale", void 0);
  27312. __decorate([
  27313. BABYLON.serialize()
  27314. ], Texture.prototype, "vScale", void 0);
  27315. __decorate([
  27316. BABYLON.serialize()
  27317. ], Texture.prototype, "uAng", void 0);
  27318. __decorate([
  27319. BABYLON.serialize()
  27320. ], Texture.prototype, "vAng", void 0);
  27321. __decorate([
  27322. BABYLON.serialize()
  27323. ], Texture.prototype, "wAng", void 0);
  27324. __decorate([
  27325. BABYLON.serialize()
  27326. ], Texture.prototype, "isBlocking", null);
  27327. return Texture;
  27328. }(BABYLON.BaseTexture));
  27329. BABYLON.Texture = Texture;
  27330. })(BABYLON || (BABYLON = {}));
  27331. //# sourceMappingURL=babylon.texture.js.map
  27332. var BABYLON;
  27333. (function (BABYLON) {
  27334. var _InstancesBatch = /** @class */ (function () {
  27335. function _InstancesBatch() {
  27336. this.mustReturn = false;
  27337. this.visibleInstances = new Array();
  27338. this.renderSelf = new Array();
  27339. }
  27340. return _InstancesBatch;
  27341. }());
  27342. BABYLON._InstancesBatch = _InstancesBatch;
  27343. var Mesh = /** @class */ (function (_super) {
  27344. __extends(Mesh, _super);
  27345. /**
  27346. * @constructor
  27347. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27348. * @param {Scene} scene The scene to add this mesh to.
  27349. * @param {Node} parent The parent of this mesh, if it has one
  27350. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27351. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27352. * When false, achieved by calling a clone(), also passing False.
  27353. * This will make creation of children, recursive.
  27354. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27355. */
  27356. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27357. if (scene === void 0) { scene = null; }
  27358. if (parent === void 0) { parent = null; }
  27359. if (source === void 0) { source = null; }
  27360. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27361. var _this = _super.call(this, name, scene) || this;
  27362. // Events
  27363. /**
  27364. * An event triggered before rendering the mesh
  27365. * @type {BABYLON.Observable}
  27366. */
  27367. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27368. /**
  27369. * An event triggered after rendering the mesh
  27370. * @type {BABYLON.Observable}
  27371. */
  27372. _this.onAfterRenderObservable = new BABYLON.Observable();
  27373. /**
  27374. * An event triggered before drawing the mesh
  27375. * @type {BABYLON.Observable}
  27376. */
  27377. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27378. // Members
  27379. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27380. _this.instances = new Array();
  27381. _this._LODLevels = new Array();
  27382. _this._visibleInstances = {};
  27383. _this._renderIdForInstances = new Array();
  27384. _this._batchCache = new _InstancesBatch();
  27385. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27386. // Use by builder only to know what orientation were the mesh build in.
  27387. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27388. _this.overrideMaterialSideOrientation = null;
  27389. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27390. // Will be used to save a source mesh reference, If any
  27391. _this._source = null;
  27392. scene = _this.getScene();
  27393. if (source) {
  27394. // Source mesh
  27395. _this._source = source;
  27396. // Geometry
  27397. if (source._geometry) {
  27398. source._geometry.applyToMesh(_this);
  27399. }
  27400. // Deep copy
  27401. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27402. // Metadata
  27403. if (source.metadata && source.metadata.clone) {
  27404. _this.metadata = source.metadata.clone();
  27405. }
  27406. else {
  27407. _this.metadata = source.metadata;
  27408. }
  27409. // Tags
  27410. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27411. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27412. }
  27413. // Parent
  27414. _this.parent = source.parent;
  27415. // Pivot
  27416. _this.setPivotMatrix(source.getPivotMatrix());
  27417. _this.id = name + "." + source.id;
  27418. // Material
  27419. _this.material = source.material;
  27420. var index;
  27421. if (!doNotCloneChildren) {
  27422. // Children
  27423. var directDescendants = source.getDescendants(true);
  27424. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27425. var child = directDescendants[index_1];
  27426. if (child.clone) {
  27427. child.clone(name + "." + child.name, _this);
  27428. }
  27429. }
  27430. }
  27431. // Physics clone
  27432. var physicsEngine = _this.getScene().getPhysicsEngine();
  27433. if (clonePhysicsImpostor && physicsEngine) {
  27434. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27435. if (impostor) {
  27436. _this.physicsImpostor = impostor.clone(_this);
  27437. }
  27438. }
  27439. // Particles
  27440. for (index = 0; index < scene.particleSystems.length; index++) {
  27441. var system = scene.particleSystems[index];
  27442. if (system.emitter === source) {
  27443. system.clone(system.name, _this);
  27444. }
  27445. }
  27446. _this.computeWorldMatrix(true);
  27447. }
  27448. // Parent
  27449. if (parent !== null) {
  27450. _this.parent = parent;
  27451. }
  27452. return _this;
  27453. }
  27454. Object.defineProperty(Mesh, "FRONTSIDE", {
  27455. /**
  27456. * Mesh side orientation : usually the external or front surface
  27457. */
  27458. get: function () {
  27459. return Mesh._FRONTSIDE;
  27460. },
  27461. enumerable: true,
  27462. configurable: true
  27463. });
  27464. Object.defineProperty(Mesh, "BACKSIDE", {
  27465. /**
  27466. * Mesh side orientation : usually the internal or back surface
  27467. */
  27468. get: function () {
  27469. return Mesh._BACKSIDE;
  27470. },
  27471. enumerable: true,
  27472. configurable: true
  27473. });
  27474. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27475. /**
  27476. * Mesh side orientation : both internal and external or front and back surfaces
  27477. */
  27478. get: function () {
  27479. return Mesh._DOUBLESIDE;
  27480. },
  27481. enumerable: true,
  27482. configurable: true
  27483. });
  27484. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27485. /**
  27486. * Mesh side orientation : by default, `FRONTSIDE`
  27487. */
  27488. get: function () {
  27489. return Mesh._DEFAULTSIDE;
  27490. },
  27491. enumerable: true,
  27492. configurable: true
  27493. });
  27494. Object.defineProperty(Mesh, "NO_CAP", {
  27495. /**
  27496. * Mesh cap setting : no cap
  27497. */
  27498. get: function () {
  27499. return Mesh._NO_CAP;
  27500. },
  27501. enumerable: true,
  27502. configurable: true
  27503. });
  27504. Object.defineProperty(Mesh, "CAP_START", {
  27505. /**
  27506. * Mesh cap setting : one cap at the beginning of the mesh
  27507. */
  27508. get: function () {
  27509. return Mesh._CAP_START;
  27510. },
  27511. enumerable: true,
  27512. configurable: true
  27513. });
  27514. Object.defineProperty(Mesh, "CAP_END", {
  27515. /**
  27516. * Mesh cap setting : one cap at the end of the mesh
  27517. */
  27518. get: function () {
  27519. return Mesh._CAP_END;
  27520. },
  27521. enumerable: true,
  27522. configurable: true
  27523. });
  27524. Object.defineProperty(Mesh, "CAP_ALL", {
  27525. /**
  27526. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27527. */
  27528. get: function () {
  27529. return Mesh._CAP_ALL;
  27530. },
  27531. enumerable: true,
  27532. configurable: true
  27533. });
  27534. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27535. set: function (callback) {
  27536. if (this._onBeforeDrawObserver) {
  27537. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27538. }
  27539. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27540. },
  27541. enumerable: true,
  27542. configurable: true
  27543. });
  27544. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27545. get: function () {
  27546. return this._morphTargetManager;
  27547. },
  27548. set: function (value) {
  27549. if (this._morphTargetManager === value) {
  27550. return;
  27551. }
  27552. this._morphTargetManager = value;
  27553. this._syncGeometryWithMorphTargetManager();
  27554. },
  27555. enumerable: true,
  27556. configurable: true
  27557. });
  27558. Object.defineProperty(Mesh.prototype, "source", {
  27559. get: function () {
  27560. return this._source;
  27561. },
  27562. enumerable: true,
  27563. configurable: true
  27564. });
  27565. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27566. get: function () {
  27567. return this._unIndexed;
  27568. },
  27569. set: function (value) {
  27570. if (this._unIndexed !== value) {
  27571. this._unIndexed = value;
  27572. this._markSubMeshesAsAttributesDirty();
  27573. }
  27574. },
  27575. enumerable: true,
  27576. configurable: true
  27577. });
  27578. // Methods
  27579. /**
  27580. * Returns the string "Mesh".
  27581. */
  27582. Mesh.prototype.getClassName = function () {
  27583. return "Mesh";
  27584. };
  27585. /**
  27586. * Returns a string.
  27587. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27588. */
  27589. Mesh.prototype.toString = function (fullDetails) {
  27590. var ret = _super.prototype.toString.call(this, fullDetails);
  27591. ret += ", n vertices: " + this.getTotalVertices();
  27592. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27593. if (this.animations) {
  27594. for (var i = 0; i < this.animations.length; i++) {
  27595. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27596. }
  27597. }
  27598. if (fullDetails) {
  27599. if (this._geometry) {
  27600. var ib = this.getIndices();
  27601. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27602. if (vb && ib) {
  27603. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27604. }
  27605. }
  27606. else {
  27607. ret += ", flat shading: UNKNOWN";
  27608. }
  27609. }
  27610. return ret;
  27611. };
  27612. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27613. /**
  27614. * True if the mesh has some Levels Of Details (LOD).
  27615. * Returns a boolean.
  27616. */
  27617. get: function () {
  27618. return this._LODLevels.length > 0;
  27619. },
  27620. enumerable: true,
  27621. configurable: true
  27622. });
  27623. /**
  27624. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27625. * @returns an array of {BABYLON.MeshLODLevel}
  27626. */
  27627. Mesh.prototype.getLODLevels = function () {
  27628. return this._LODLevels;
  27629. };
  27630. Mesh.prototype._sortLODLevels = function () {
  27631. this._LODLevels.sort(function (a, b) {
  27632. if (a.distance < b.distance) {
  27633. return 1;
  27634. }
  27635. if (a.distance > b.distance) {
  27636. return -1;
  27637. }
  27638. return 0;
  27639. });
  27640. };
  27641. /**
  27642. * Add a mesh as LOD level triggered at the given distance.
  27643. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27644. * @param {number} distance The distance from the center of the object to show this level
  27645. * @param {Mesh} mesh The mesh to be added as LOD level
  27646. * @return {Mesh} This mesh (for chaining)
  27647. */
  27648. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27649. if (mesh && mesh._masterMesh) {
  27650. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27651. return this;
  27652. }
  27653. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27654. this._LODLevels.push(level);
  27655. if (mesh) {
  27656. mesh._masterMesh = this;
  27657. }
  27658. this._sortLODLevels();
  27659. return this;
  27660. };
  27661. /**
  27662. * Returns the LOD level mesh at the passed distance or null if not found.
  27663. * It is related to the method `addLODLevel(distance, mesh)`.
  27664. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27665. * Returns an object Mesh or `null`.
  27666. */
  27667. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27668. for (var index = 0; index < this._LODLevels.length; index++) {
  27669. var level = this._LODLevels[index];
  27670. if (level.distance === distance) {
  27671. return level.mesh;
  27672. }
  27673. }
  27674. return null;
  27675. };
  27676. /**
  27677. * Remove a mesh from the LOD array
  27678. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27679. * @param {Mesh} mesh The mesh to be removed.
  27680. * @return {Mesh} This mesh (for chaining)
  27681. */
  27682. Mesh.prototype.removeLODLevel = function (mesh) {
  27683. for (var index = 0; index < this._LODLevels.length; index++) {
  27684. if (this._LODLevels[index].mesh === mesh) {
  27685. this._LODLevels.splice(index, 1);
  27686. if (mesh) {
  27687. mesh._masterMesh = null;
  27688. }
  27689. }
  27690. }
  27691. this._sortLODLevels();
  27692. return this;
  27693. };
  27694. /**
  27695. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27696. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27697. */
  27698. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27699. if (!this._LODLevels || this._LODLevels.length === 0) {
  27700. return this;
  27701. }
  27702. var bSphere;
  27703. if (boundingSphere) {
  27704. bSphere = boundingSphere;
  27705. }
  27706. else {
  27707. var boundingInfo = this.getBoundingInfo();
  27708. bSphere = boundingInfo.boundingSphere;
  27709. }
  27710. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27711. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27712. if (this.onLODLevelSelection) {
  27713. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27714. }
  27715. return this;
  27716. }
  27717. for (var index = 0; index < this._LODLevels.length; index++) {
  27718. var level = this._LODLevels[index];
  27719. if (level.distance < distanceToCamera) {
  27720. if (level.mesh) {
  27721. level.mesh._preActivate();
  27722. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27723. }
  27724. if (this.onLODLevelSelection) {
  27725. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27726. }
  27727. return level.mesh;
  27728. }
  27729. }
  27730. if (this.onLODLevelSelection) {
  27731. this.onLODLevelSelection(distanceToCamera, this, this);
  27732. }
  27733. return this;
  27734. };
  27735. Object.defineProperty(Mesh.prototype, "geometry", {
  27736. /**
  27737. * Returns the mesh internal Geometry object.
  27738. */
  27739. get: function () {
  27740. return this._geometry;
  27741. },
  27742. enumerable: true,
  27743. configurable: true
  27744. });
  27745. /**
  27746. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27747. */
  27748. Mesh.prototype.getTotalVertices = function () {
  27749. if (this._geometry === null || this._geometry === undefined) {
  27750. return 0;
  27751. }
  27752. return this._geometry.getTotalVertices();
  27753. };
  27754. /**
  27755. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27756. * 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.
  27757. * You can force the copy with forceCopy === true
  27758. * Returns null if the mesh has no geometry or no vertex buffer.
  27759. * Possible `kind` values :
  27760. * - BABYLON.VertexBuffer.PositionKind
  27761. * - BABYLON.VertexBuffer.UVKind
  27762. * - BABYLON.VertexBuffer.UV2Kind
  27763. * - BABYLON.VertexBuffer.UV3Kind
  27764. * - BABYLON.VertexBuffer.UV4Kind
  27765. * - BABYLON.VertexBuffer.UV5Kind
  27766. * - BABYLON.VertexBuffer.UV6Kind
  27767. * - BABYLON.VertexBuffer.ColorKind
  27768. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27769. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27770. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27771. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27772. */
  27773. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27774. if (!this._geometry) {
  27775. return null;
  27776. }
  27777. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27778. };
  27779. /**
  27780. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27781. * Returns `null` if the mesh has no geometry.
  27782. * Possible `kind` values :
  27783. * - BABYLON.VertexBuffer.PositionKind
  27784. * - BABYLON.VertexBuffer.UVKind
  27785. * - BABYLON.VertexBuffer.UV2Kind
  27786. * - BABYLON.VertexBuffer.UV3Kind
  27787. * - BABYLON.VertexBuffer.UV4Kind
  27788. * - BABYLON.VertexBuffer.UV5Kind
  27789. * - BABYLON.VertexBuffer.UV6Kind
  27790. * - BABYLON.VertexBuffer.ColorKind
  27791. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27792. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27793. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27794. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27795. */
  27796. Mesh.prototype.getVertexBuffer = function (kind) {
  27797. if (!this._geometry) {
  27798. return null;
  27799. }
  27800. return this._geometry.getVertexBuffer(kind);
  27801. };
  27802. /**
  27803. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27804. * Possible `kind` values :
  27805. * - BABYLON.VertexBuffer.PositionKind
  27806. * - BABYLON.VertexBuffer.UVKind
  27807. * - BABYLON.VertexBuffer.UV2Kind
  27808. * - BABYLON.VertexBuffer.UV3Kind
  27809. * - BABYLON.VertexBuffer.UV4Kind
  27810. * - BABYLON.VertexBuffer.UV5Kind
  27811. * - BABYLON.VertexBuffer.UV6Kind
  27812. * - BABYLON.VertexBuffer.ColorKind
  27813. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27814. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27815. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27816. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27817. */
  27818. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27819. if (!this._geometry) {
  27820. if (this._delayInfo) {
  27821. return this._delayInfo.indexOf(kind) !== -1;
  27822. }
  27823. return false;
  27824. }
  27825. return this._geometry.isVerticesDataPresent(kind);
  27826. };
  27827. /**
  27828. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27829. * Possible `kind` values :
  27830. * - BABYLON.VertexBuffer.PositionKind
  27831. * - BABYLON.VertexBuffer.UVKind
  27832. * - BABYLON.VertexBuffer.UV2Kind
  27833. * - BABYLON.VertexBuffer.UV3Kind
  27834. * - BABYLON.VertexBuffer.UV4Kind
  27835. * - BABYLON.VertexBuffer.UV5Kind
  27836. * - BABYLON.VertexBuffer.UV6Kind
  27837. * - BABYLON.VertexBuffer.ColorKind
  27838. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27839. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27840. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27841. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27842. */
  27843. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27844. if (!this._geometry) {
  27845. if (this._delayInfo) {
  27846. return this._delayInfo.indexOf(kind) !== -1;
  27847. }
  27848. return false;
  27849. }
  27850. return this._geometry.isVertexBufferUpdatable(kind);
  27851. };
  27852. /**
  27853. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27854. * Possible `kind` values :
  27855. * - BABYLON.VertexBuffer.PositionKind
  27856. * - BABYLON.VertexBuffer.UVKind
  27857. * - BABYLON.VertexBuffer.UV2Kind
  27858. * - BABYLON.VertexBuffer.UV3Kind
  27859. * - BABYLON.VertexBuffer.UV4Kind
  27860. * - BABYLON.VertexBuffer.UV5Kind
  27861. * - BABYLON.VertexBuffer.UV6Kind
  27862. * - BABYLON.VertexBuffer.ColorKind
  27863. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27864. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27865. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27866. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27867. */
  27868. Mesh.prototype.getVerticesDataKinds = function () {
  27869. if (!this._geometry) {
  27870. var result = new Array();
  27871. if (this._delayInfo) {
  27872. this._delayInfo.forEach(function (kind, index, array) {
  27873. result.push(kind);
  27874. });
  27875. }
  27876. return result;
  27877. }
  27878. return this._geometry.getVerticesDataKinds();
  27879. };
  27880. /**
  27881. * Returns a positive integer : the total number of indices in this mesh geometry.
  27882. * Returns zero if the mesh has no geometry.
  27883. */
  27884. Mesh.prototype.getTotalIndices = function () {
  27885. if (!this._geometry) {
  27886. return 0;
  27887. }
  27888. return this._geometry.getTotalIndices();
  27889. };
  27890. /**
  27891. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27892. * 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.
  27893. * Returns an empty array if the mesh has no geometry.
  27894. */
  27895. Mesh.prototype.getIndices = function (copyWhenShared) {
  27896. if (!this._geometry) {
  27897. return [];
  27898. }
  27899. return this._geometry.getIndices(copyWhenShared);
  27900. };
  27901. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27902. get: function () {
  27903. return this._masterMesh !== null && this._masterMesh !== undefined;
  27904. },
  27905. enumerable: true,
  27906. configurable: true
  27907. });
  27908. /**
  27909. * Determine if the current mesh is ready to be rendered
  27910. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27911. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27912. * @returns true if all associated assets are ready (material, textures, shaders)
  27913. */
  27914. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27915. if (completeCheck === void 0) { completeCheck = false; }
  27916. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27917. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27918. return false;
  27919. }
  27920. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27921. return false;
  27922. }
  27923. if (!this.subMeshes || this.subMeshes.length === 0) {
  27924. return true;
  27925. }
  27926. if (!completeCheck) {
  27927. return true;
  27928. }
  27929. var engine = this.getEngine();
  27930. var scene = this.getScene();
  27931. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27932. this.computeWorldMatrix();
  27933. var mat = this.material || scene.defaultMaterial;
  27934. if (mat) {
  27935. if (mat.storeEffectOnSubMeshes) {
  27936. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27937. var subMesh = _a[_i];
  27938. var effectiveMaterial = subMesh.getMaterial();
  27939. if (effectiveMaterial) {
  27940. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27941. return false;
  27942. }
  27943. }
  27944. }
  27945. }
  27946. else {
  27947. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27948. return false;
  27949. }
  27950. }
  27951. }
  27952. // Shadows
  27953. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27954. var light = _c[_b];
  27955. var generator = light.getShadowGenerator();
  27956. if (generator) {
  27957. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27958. var subMesh = _e[_d];
  27959. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27960. return false;
  27961. }
  27962. }
  27963. }
  27964. }
  27965. // LOD
  27966. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27967. var lod = _g[_f];
  27968. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27969. return false;
  27970. }
  27971. }
  27972. return true;
  27973. };
  27974. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27975. /**
  27976. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27977. * This property is pertinent only for updatable parametric shapes.
  27978. */
  27979. get: function () {
  27980. return this._areNormalsFrozen;
  27981. },
  27982. enumerable: true,
  27983. configurable: true
  27984. });
  27985. /**
  27986. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27987. * It has no effect at all on other shapes.
  27988. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27989. * Returns the Mesh.
  27990. */
  27991. Mesh.prototype.freezeNormals = function () {
  27992. this._areNormalsFrozen = true;
  27993. return this;
  27994. };
  27995. /**
  27996. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27997. * It has no effect at all on other shapes.
  27998. * It reactivates the mesh normals computation if it was previously frozen.
  27999. * Returns the Mesh.
  28000. */
  28001. Mesh.prototype.unfreezeNormals = function () {
  28002. this._areNormalsFrozen = false;
  28003. return this;
  28004. };
  28005. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28006. /**
  28007. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28008. */
  28009. set: function (count) {
  28010. this._overridenInstanceCount = count;
  28011. },
  28012. enumerable: true,
  28013. configurable: true
  28014. });
  28015. // Methods
  28016. Mesh.prototype._preActivate = function () {
  28017. var sceneRenderId = this.getScene().getRenderId();
  28018. if (this._preActivateId === sceneRenderId) {
  28019. return this;
  28020. }
  28021. this._preActivateId = sceneRenderId;
  28022. this._visibleInstances = null;
  28023. return this;
  28024. };
  28025. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28026. if (this._visibleInstances) {
  28027. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28028. }
  28029. return this;
  28030. };
  28031. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28032. if (!this._visibleInstances) {
  28033. this._visibleInstances = {};
  28034. this._visibleInstances.defaultRenderId = renderId;
  28035. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28036. }
  28037. if (!this._visibleInstances[renderId]) {
  28038. this._visibleInstances[renderId] = new Array();
  28039. }
  28040. this._visibleInstances[renderId].push(instance);
  28041. return this;
  28042. };
  28043. /**
  28044. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28045. * This means the mesh underlying bounding box and sphere are recomputed.
  28046. * Returns the Mesh.
  28047. */
  28048. Mesh.prototype.refreshBoundingInfo = function () {
  28049. return this._refreshBoundingInfo(false);
  28050. };
  28051. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28052. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28053. return this;
  28054. }
  28055. var data = this._getPositionData(applySkeleton);
  28056. if (data) {
  28057. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28058. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28059. }
  28060. if (this.subMeshes) {
  28061. for (var index = 0; index < this.subMeshes.length; index++) {
  28062. this.subMeshes[index].refreshBoundingInfo();
  28063. }
  28064. }
  28065. this._updateBoundingInfo();
  28066. return this;
  28067. };
  28068. Mesh.prototype._getPositionData = function (applySkeleton) {
  28069. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28070. if (data && applySkeleton && this.skeleton) {
  28071. data = BABYLON.Tools.Slice(data);
  28072. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28073. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28074. if (matricesWeightsData && matricesIndicesData) {
  28075. var needExtras = this.numBoneInfluencers > 4;
  28076. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28077. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28078. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28079. var tempVector = BABYLON.Tmp.Vector3[0];
  28080. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28081. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28082. var matWeightIdx = 0;
  28083. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28084. finalMatrix.reset();
  28085. var inf;
  28086. var weight;
  28087. for (inf = 0; inf < 4; inf++) {
  28088. weight = matricesWeightsData[matWeightIdx + inf];
  28089. if (weight <= 0)
  28090. break;
  28091. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28092. finalMatrix.addToSelf(tempMatrix);
  28093. }
  28094. if (needExtras) {
  28095. for (inf = 0; inf < 4; inf++) {
  28096. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28097. if (weight <= 0)
  28098. break;
  28099. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28100. finalMatrix.addToSelf(tempMatrix);
  28101. }
  28102. }
  28103. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28104. tempVector.toArray(data, index);
  28105. }
  28106. }
  28107. }
  28108. return data;
  28109. };
  28110. Mesh.prototype._createGlobalSubMesh = function (force) {
  28111. var totalVertices = this.getTotalVertices();
  28112. if (!totalVertices || !this.getIndices()) {
  28113. return null;
  28114. }
  28115. // Check if we need to recreate the submeshes
  28116. if (this.subMeshes && this.subMeshes.length > 0) {
  28117. var ib = this.getIndices();
  28118. if (!ib) {
  28119. return null;
  28120. }
  28121. var totalIndices = ib.length;
  28122. var needToRecreate = false;
  28123. if (force) {
  28124. needToRecreate = true;
  28125. }
  28126. else {
  28127. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28128. var submesh = _a[_i];
  28129. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28130. needToRecreate = true;
  28131. break;
  28132. }
  28133. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28134. needToRecreate = true;
  28135. break;
  28136. }
  28137. }
  28138. }
  28139. if (!needToRecreate) {
  28140. return this.subMeshes[0];
  28141. }
  28142. }
  28143. this.releaseSubMeshes();
  28144. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28145. };
  28146. Mesh.prototype.subdivide = function (count) {
  28147. if (count < 1) {
  28148. return;
  28149. }
  28150. var totalIndices = this.getTotalIndices();
  28151. var subdivisionSize = (totalIndices / count) | 0;
  28152. var offset = 0;
  28153. // Ensure that subdivisionSize is a multiple of 3
  28154. while (subdivisionSize % 3 !== 0) {
  28155. subdivisionSize++;
  28156. }
  28157. this.releaseSubMeshes();
  28158. for (var index = 0; index < count; index++) {
  28159. if (offset >= totalIndices) {
  28160. break;
  28161. }
  28162. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28163. offset += subdivisionSize;
  28164. }
  28165. this.synchronizeInstances();
  28166. };
  28167. /**
  28168. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28169. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28170. * The `data` are either a numeric array either a Float32Array.
  28171. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28172. * 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).
  28173. * Note that a new underlying VertexBuffer object is created each call.
  28174. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28175. *
  28176. * Possible `kind` values :
  28177. * - BABYLON.VertexBuffer.PositionKind
  28178. * - BABYLON.VertexBuffer.UVKind
  28179. * - BABYLON.VertexBuffer.UV2Kind
  28180. * - BABYLON.VertexBuffer.UV3Kind
  28181. * - BABYLON.VertexBuffer.UV4Kind
  28182. * - BABYLON.VertexBuffer.UV5Kind
  28183. * - BABYLON.VertexBuffer.UV6Kind
  28184. * - BABYLON.VertexBuffer.ColorKind
  28185. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28186. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28187. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28188. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28189. *
  28190. * Returns the Mesh.
  28191. */
  28192. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28193. if (updatable === void 0) { updatable = false; }
  28194. if (!this._geometry) {
  28195. var vertexData = new BABYLON.VertexData();
  28196. vertexData.set(data, kind);
  28197. var scene = this.getScene();
  28198. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28199. }
  28200. else {
  28201. this._geometry.setVerticesData(kind, data, updatable, stride);
  28202. }
  28203. return this;
  28204. };
  28205. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28206. if (updatable === void 0) { updatable = true; }
  28207. var vb = this.getVertexBuffer(kind);
  28208. if (!vb || vb.isUpdatable() === updatable) {
  28209. return;
  28210. }
  28211. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28212. };
  28213. /**
  28214. * Sets the mesh VertexBuffer.
  28215. * Returns the Mesh.
  28216. */
  28217. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28218. if (!this._geometry) {
  28219. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28220. }
  28221. this._geometry.setVerticesBuffer(buffer);
  28222. return this;
  28223. };
  28224. /**
  28225. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28226. * If the mesh has no geometry, it is simply returned as it is.
  28227. * The `data` are either a numeric array either a Float32Array.
  28228. * No new underlying VertexBuffer object is created.
  28229. * 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.
  28230. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28231. *
  28232. * Possible `kind` values :
  28233. * - BABYLON.VertexBuffer.PositionKind
  28234. * - BABYLON.VertexBuffer.UVKind
  28235. * - BABYLON.VertexBuffer.UV2Kind
  28236. * - BABYLON.VertexBuffer.UV3Kind
  28237. * - BABYLON.VertexBuffer.UV4Kind
  28238. * - BABYLON.VertexBuffer.UV5Kind
  28239. * - BABYLON.VertexBuffer.UV6Kind
  28240. * - BABYLON.VertexBuffer.ColorKind
  28241. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28242. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28243. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28244. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28245. *
  28246. * Returns the Mesh.
  28247. */
  28248. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28249. if (!this._geometry) {
  28250. return this;
  28251. }
  28252. if (!makeItUnique) {
  28253. this._geometry.updateVerticesData(kind, data, updateExtends);
  28254. }
  28255. else {
  28256. this.makeGeometryUnique();
  28257. this.updateVerticesData(kind, data, updateExtends, false);
  28258. }
  28259. return this;
  28260. };
  28261. /**
  28262. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28263. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28264. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28265. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28266. * Returns the Mesh.
  28267. */
  28268. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28269. if (computeNormals === void 0) { computeNormals = true; }
  28270. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28271. if (!positions) {
  28272. return this;
  28273. }
  28274. positionFunction(positions);
  28275. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28276. if (computeNormals) {
  28277. var indices = this.getIndices();
  28278. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28279. if (!normals) {
  28280. return this;
  28281. }
  28282. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28283. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28284. }
  28285. return this;
  28286. };
  28287. /**
  28288. * Creates a un-shared specific occurence of the geometry for the mesh.
  28289. * Returns the Mesh.
  28290. */
  28291. Mesh.prototype.makeGeometryUnique = function () {
  28292. if (!this._geometry) {
  28293. return this;
  28294. }
  28295. var oldGeometry = this._geometry;
  28296. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28297. oldGeometry.releaseForMesh(this, true);
  28298. geometry.applyToMesh(this);
  28299. return this;
  28300. };
  28301. /**
  28302. * Sets the mesh indices.
  28303. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28304. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28305. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28306. * This method creates a new index buffer each call.
  28307. * Returns the Mesh.
  28308. */
  28309. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28310. if (totalVertices === void 0) { totalVertices = null; }
  28311. if (updatable === void 0) { updatable = false; }
  28312. if (!this._geometry) {
  28313. var vertexData = new BABYLON.VertexData();
  28314. vertexData.indices = indices;
  28315. var scene = this.getScene();
  28316. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28317. }
  28318. else {
  28319. this._geometry.setIndices(indices, totalVertices, updatable);
  28320. }
  28321. return this;
  28322. };
  28323. /**
  28324. * Update the current index buffer
  28325. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28326. * Returns the Mesh.
  28327. */
  28328. Mesh.prototype.updateIndices = function (indices, offset) {
  28329. if (!this._geometry) {
  28330. return this;
  28331. }
  28332. this._geometry.updateIndices(indices, offset);
  28333. return this;
  28334. };
  28335. /**
  28336. * Invert the geometry to move from a right handed system to a left handed one.
  28337. * Returns the Mesh.
  28338. */
  28339. Mesh.prototype.toLeftHanded = function () {
  28340. if (!this._geometry) {
  28341. return this;
  28342. }
  28343. this._geometry.toLeftHanded();
  28344. return this;
  28345. };
  28346. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28347. if (!this._geometry) {
  28348. return this;
  28349. }
  28350. var engine = this.getScene().getEngine();
  28351. // Wireframe
  28352. var indexToBind;
  28353. if (this._unIndexed) {
  28354. indexToBind = null;
  28355. }
  28356. else {
  28357. switch (fillMode) {
  28358. case BABYLON.Material.PointFillMode:
  28359. indexToBind = null;
  28360. break;
  28361. case BABYLON.Material.WireFrameFillMode:
  28362. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28363. break;
  28364. default:
  28365. case BABYLON.Material.TriangleFillMode:
  28366. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28367. break;
  28368. }
  28369. }
  28370. // VBOs
  28371. this._geometry._bind(effect, indexToBind);
  28372. return this;
  28373. };
  28374. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28375. if (alternate === void 0) { alternate = false; }
  28376. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28377. return this;
  28378. }
  28379. this.onBeforeDrawObservable.notifyObservers(this);
  28380. var scene = this.getScene();
  28381. var engine = scene.getEngine();
  28382. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28383. // or triangles as points
  28384. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28385. }
  28386. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28387. // Triangles as wireframe
  28388. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28389. }
  28390. else {
  28391. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28392. }
  28393. if (scene._isAlternateRenderingEnabled && !alternate) {
  28394. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28395. if (!effect || !scene.activeCamera) {
  28396. return this;
  28397. }
  28398. scene._switchToAlternateCameraConfiguration(true);
  28399. this._effectiveMaterial.bindView(effect);
  28400. this._effectiveMaterial.bindViewProjection(effect);
  28401. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28402. this._draw(subMesh, fillMode, instancesCount, true);
  28403. engine.setViewport(scene.activeCamera.viewport);
  28404. scene._switchToAlternateCameraConfiguration(false);
  28405. this._effectiveMaterial.bindView(effect);
  28406. this._effectiveMaterial.bindViewProjection(effect);
  28407. }
  28408. return this;
  28409. };
  28410. /**
  28411. * Registers for this mesh a javascript function called just before the rendering process.
  28412. * This function is passed the current mesh.
  28413. * Return the Mesh.
  28414. */
  28415. Mesh.prototype.registerBeforeRender = function (func) {
  28416. this.onBeforeRenderObservable.add(func);
  28417. return this;
  28418. };
  28419. /**
  28420. * Disposes a previously registered javascript function called before the rendering.
  28421. * This function is passed the current mesh.
  28422. * Returns the Mesh.
  28423. */
  28424. Mesh.prototype.unregisterBeforeRender = function (func) {
  28425. this.onBeforeRenderObservable.removeCallback(func);
  28426. return this;
  28427. };
  28428. /**
  28429. * Registers for this mesh a javascript function called just after the rendering is complete.
  28430. * This function is passed the current mesh.
  28431. * Returns the Mesh.
  28432. */
  28433. Mesh.prototype.registerAfterRender = function (func) {
  28434. this.onAfterRenderObservable.add(func);
  28435. return this;
  28436. };
  28437. /**
  28438. * Disposes a previously registered javascript function called after the rendering.
  28439. * This function is passed the current mesh.
  28440. * Return the Mesh.
  28441. */
  28442. Mesh.prototype.unregisterAfterRender = function (func) {
  28443. this.onAfterRenderObservable.removeCallback(func);
  28444. return this;
  28445. };
  28446. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28447. var scene = this.getScene();
  28448. this._batchCache.mustReturn = false;
  28449. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28450. this._batchCache.visibleInstances[subMeshId] = null;
  28451. if (this._visibleInstances) {
  28452. var currentRenderId = scene.getRenderId();
  28453. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28454. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28455. var selfRenderId = this._renderId;
  28456. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28457. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28458. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28459. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28460. }
  28461. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28462. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28463. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28464. this._batchCache.mustReturn = true;
  28465. return this._batchCache;
  28466. }
  28467. if (currentRenderId !== selfRenderId) {
  28468. this._batchCache.renderSelf[subMeshId] = false;
  28469. }
  28470. }
  28471. this._renderIdForInstances[subMeshId] = currentRenderId;
  28472. }
  28473. return this._batchCache;
  28474. };
  28475. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28476. var visibleInstances = batch.visibleInstances[subMesh._id];
  28477. if (!visibleInstances) {
  28478. return this;
  28479. }
  28480. var matricesCount = visibleInstances.length + 1;
  28481. var bufferSize = matricesCount * 16 * 4;
  28482. var currentInstancesBufferSize = this._instancesBufferSize;
  28483. var instancesBuffer = this._instancesBuffer;
  28484. while (this._instancesBufferSize < bufferSize) {
  28485. this._instancesBufferSize *= 2;
  28486. }
  28487. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28488. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28489. }
  28490. var offset = 0;
  28491. var instancesCount = 0;
  28492. var world = this.getWorldMatrix();
  28493. if (batch.renderSelf[subMesh._id]) {
  28494. world.copyToArray(this._instancesData, offset);
  28495. offset += 16;
  28496. instancesCount++;
  28497. }
  28498. if (visibleInstances) {
  28499. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28500. var instance = visibleInstances[instanceIndex];
  28501. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28502. offset += 16;
  28503. instancesCount++;
  28504. }
  28505. }
  28506. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28507. if (instancesBuffer) {
  28508. instancesBuffer.dispose();
  28509. }
  28510. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28511. this._instancesBuffer = instancesBuffer;
  28512. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28513. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28514. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28515. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28516. }
  28517. else {
  28518. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28519. }
  28520. this._bind(subMesh, effect, fillMode);
  28521. this._draw(subMesh, fillMode, instancesCount);
  28522. engine.unbindInstanceAttributes();
  28523. return this;
  28524. };
  28525. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28526. var scene = this.getScene();
  28527. var engine = scene.getEngine();
  28528. if (hardwareInstancedRendering) {
  28529. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28530. }
  28531. else {
  28532. if (batch.renderSelf[subMesh._id]) {
  28533. // Draw
  28534. if (onBeforeDraw) {
  28535. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28536. }
  28537. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28538. }
  28539. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28540. if (visibleInstancesForSubMesh) {
  28541. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28542. var instance = visibleInstancesForSubMesh[instanceIndex];
  28543. // World
  28544. var world = instance.getWorldMatrix();
  28545. if (onBeforeDraw) {
  28546. onBeforeDraw(true, world, effectiveMaterial);
  28547. }
  28548. // Draw
  28549. this._draw(subMesh, fillMode);
  28550. }
  28551. }
  28552. }
  28553. return this;
  28554. };
  28555. /**
  28556. * Triggers the draw call for the mesh.
  28557. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28558. * Returns the Mesh.
  28559. */
  28560. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28561. this.checkOcclusionQuery();
  28562. if (this._isOccluded) {
  28563. return this;
  28564. }
  28565. var scene = this.getScene();
  28566. // Managing instances
  28567. var batch = this._getInstancesRenderList(subMesh._id);
  28568. if (batch.mustReturn) {
  28569. return this;
  28570. }
  28571. // Checking geometry state
  28572. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28573. return this;
  28574. }
  28575. this.onBeforeRenderObservable.notifyObservers(this);
  28576. var engine = scene.getEngine();
  28577. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28578. // Material
  28579. var material = subMesh.getMaterial();
  28580. if (!material) {
  28581. return this;
  28582. }
  28583. this._effectiveMaterial = material;
  28584. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28585. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28586. return this;
  28587. }
  28588. }
  28589. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28590. return this;
  28591. }
  28592. // Alpha mode
  28593. if (enableAlphaMode) {
  28594. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28595. }
  28596. // Outline - step 1
  28597. var savedDepthWrite = engine.getDepthWrite();
  28598. if (this.renderOutline) {
  28599. engine.setDepthWrite(false);
  28600. scene.getOutlineRenderer().render(subMesh, batch);
  28601. engine.setDepthWrite(savedDepthWrite);
  28602. }
  28603. var effect;
  28604. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28605. effect = subMesh.effect;
  28606. }
  28607. else {
  28608. effect = this._effectiveMaterial.getEffect();
  28609. }
  28610. if (!effect) {
  28611. return this;
  28612. }
  28613. var sideOrientation = this.overrideMaterialSideOrientation;
  28614. if (sideOrientation == null) {
  28615. sideOrientation = this._effectiveMaterial.sideOrientation;
  28616. if (this._getWorldMatrixDeterminant() < 0) {
  28617. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28618. }
  28619. }
  28620. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28621. if (this._effectiveMaterial.forceDepthWrite) {
  28622. engine.setDepthWrite(true);
  28623. }
  28624. // Bind
  28625. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28626. if (!hardwareInstancedRendering) {
  28627. this._bind(subMesh, effect, fillMode);
  28628. }
  28629. var world = this.getWorldMatrix();
  28630. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28631. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28632. }
  28633. else {
  28634. this._effectiveMaterial.bind(world, this);
  28635. }
  28636. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28637. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28638. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28639. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28640. }
  28641. // Draw
  28642. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28643. // Unbind
  28644. this._effectiveMaterial.unbind();
  28645. // Outline - step 2
  28646. if (this.renderOutline && savedDepthWrite) {
  28647. engine.setDepthWrite(true);
  28648. engine.setColorWrite(false);
  28649. scene.getOutlineRenderer().render(subMesh, batch);
  28650. engine.setColorWrite(true);
  28651. }
  28652. // Overlay
  28653. if (this.renderOverlay) {
  28654. var currentMode = engine.getAlphaMode();
  28655. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28656. scene.getOutlineRenderer().render(subMesh, batch, true);
  28657. engine.setAlphaMode(currentMode);
  28658. }
  28659. this.onAfterRenderObservable.notifyObservers(this);
  28660. return this;
  28661. };
  28662. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28663. if (isInstance && effectiveMaterial) {
  28664. effectiveMaterial.bindOnlyWorldMatrix(world);
  28665. }
  28666. };
  28667. /**
  28668. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28669. */
  28670. Mesh.prototype.getEmittedParticleSystems = function () {
  28671. var results = new Array();
  28672. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28673. var particleSystem = this.getScene().particleSystems[index];
  28674. if (particleSystem.emitter === this) {
  28675. results.push(particleSystem);
  28676. }
  28677. }
  28678. return results;
  28679. };
  28680. /**
  28681. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28682. */
  28683. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28684. var results = new Array();
  28685. var descendants = this.getDescendants();
  28686. descendants.push(this);
  28687. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28688. var particleSystem = this.getScene().particleSystems[index];
  28689. var emitter = particleSystem.emitter;
  28690. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28691. results.push(particleSystem);
  28692. }
  28693. }
  28694. return results;
  28695. };
  28696. Mesh.prototype._checkDelayState = function () {
  28697. var scene = this.getScene();
  28698. if (this._geometry) {
  28699. this._geometry.load(scene);
  28700. }
  28701. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28702. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28703. this._queueLoad(scene);
  28704. }
  28705. return this;
  28706. };
  28707. Mesh.prototype._queueLoad = function (scene) {
  28708. var _this = this;
  28709. scene._addPendingData(this);
  28710. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28711. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28712. if (data instanceof ArrayBuffer) {
  28713. _this._delayLoadingFunction(data, _this);
  28714. }
  28715. else {
  28716. _this._delayLoadingFunction(JSON.parse(data), _this);
  28717. }
  28718. _this.instances.forEach(function (instance) {
  28719. instance._syncSubMeshes();
  28720. });
  28721. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28722. scene._removePendingData(_this);
  28723. }, function () { }, scene.database, getBinaryData);
  28724. return this;
  28725. };
  28726. /**
  28727. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28728. */
  28729. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28730. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28731. return false;
  28732. }
  28733. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28734. return false;
  28735. }
  28736. this._checkDelayState();
  28737. return true;
  28738. };
  28739. /**
  28740. * Sets the mesh material by the material or multiMaterial `id` property.
  28741. * The material `id` is a string identifying the material or the multiMaterial.
  28742. * This method returns the Mesh.
  28743. */
  28744. Mesh.prototype.setMaterialByID = function (id) {
  28745. var materials = this.getScene().materials;
  28746. var index;
  28747. for (index = materials.length - 1; index > -1; index--) {
  28748. if (materials[index].id === id) {
  28749. this.material = materials[index];
  28750. return this;
  28751. }
  28752. }
  28753. // Multi
  28754. var multiMaterials = this.getScene().multiMaterials;
  28755. for (index = multiMaterials.length - 1; index > -1; index--) {
  28756. if (multiMaterials[index].id === id) {
  28757. this.material = multiMaterials[index];
  28758. return this;
  28759. }
  28760. }
  28761. return this;
  28762. };
  28763. /**
  28764. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28765. */
  28766. Mesh.prototype.getAnimatables = function () {
  28767. var results = new Array();
  28768. if (this.material) {
  28769. results.push(this.material);
  28770. }
  28771. if (this.skeleton) {
  28772. results.push(this.skeleton);
  28773. }
  28774. return results;
  28775. };
  28776. /**
  28777. * Modifies the mesh geometry according to the passed transformation matrix.
  28778. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28779. * The mesh normals are modified accordingly the same transformation.
  28780. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28781. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28782. * Returns the Mesh.
  28783. */
  28784. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28785. // Position
  28786. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28787. return this;
  28788. }
  28789. var submeshes = this.subMeshes.splice(0);
  28790. this._resetPointsArrayCache();
  28791. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28792. var temp = new Array();
  28793. var index;
  28794. for (index = 0; index < data.length; index += 3) {
  28795. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28796. }
  28797. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28798. // Normals
  28799. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28800. return this;
  28801. }
  28802. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28803. temp = [];
  28804. for (index = 0; index < data.length; index += 3) {
  28805. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28806. }
  28807. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28808. // flip faces?
  28809. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28810. this.flipFaces();
  28811. }
  28812. // Restore submeshes
  28813. this.releaseSubMeshes();
  28814. this.subMeshes = submeshes;
  28815. return this;
  28816. };
  28817. /**
  28818. * Modifies the mesh geometry according to its own current World Matrix.
  28819. * The mesh World Matrix is then reset.
  28820. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28821. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28822. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28823. * Returns the Mesh.
  28824. */
  28825. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28826. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28827. this.scaling.copyFromFloats(1, 1, 1);
  28828. this.position.copyFromFloats(0, 0, 0);
  28829. this.rotation.copyFromFloats(0, 0, 0);
  28830. //only if quaternion is already set
  28831. if (this.rotationQuaternion) {
  28832. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28833. }
  28834. this._worldMatrix = BABYLON.Matrix.Identity();
  28835. return this;
  28836. };
  28837. Object.defineProperty(Mesh.prototype, "_positions", {
  28838. // Cache
  28839. get: function () {
  28840. if (this._geometry) {
  28841. return this._geometry._positions;
  28842. }
  28843. return null;
  28844. },
  28845. enumerable: true,
  28846. configurable: true
  28847. });
  28848. Mesh.prototype._resetPointsArrayCache = function () {
  28849. if (this._geometry) {
  28850. this._geometry._resetPointsArrayCache();
  28851. }
  28852. return this;
  28853. };
  28854. Mesh.prototype._generatePointsArray = function () {
  28855. if (this._geometry) {
  28856. return this._geometry._generatePointsArray();
  28857. }
  28858. return false;
  28859. };
  28860. /**
  28861. * Returns a new Mesh object generated from the current mesh properties.
  28862. * This method must not get confused with createInstance().
  28863. * The parameter `name` is a string, the name given to the new mesh.
  28864. * The optional parameter `newParent` can be any Node object (default `null`).
  28865. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28866. * 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.
  28867. */
  28868. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28869. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28870. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28871. };
  28872. /**
  28873. * Releases resources associated with this mesh.
  28874. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28875. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28876. */
  28877. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28878. var _this = this;
  28879. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28880. this.morphTargetManager = null;
  28881. if (this._geometry) {
  28882. this._geometry.releaseForMesh(this, true);
  28883. }
  28884. // Sources
  28885. var meshes = this.getScene().meshes;
  28886. meshes.forEach(function (abstractMesh) {
  28887. var mesh = abstractMesh;
  28888. if (mesh._source && mesh._source === _this) {
  28889. mesh._source = null;
  28890. }
  28891. });
  28892. this._source = null;
  28893. // Instances
  28894. if (this._instancesBuffer) {
  28895. this._instancesBuffer.dispose();
  28896. this._instancesBuffer = null;
  28897. }
  28898. while (this.instances.length) {
  28899. this.instances[0].dispose();
  28900. }
  28901. // Effect layers.
  28902. var effectLayers = this.getScene().effectLayers;
  28903. for (var i = 0; i < effectLayers.length; i++) {
  28904. var effectLayer = effectLayers[i];
  28905. if (effectLayer) {
  28906. effectLayer._disposeMesh(this);
  28907. }
  28908. }
  28909. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28910. };
  28911. /**
  28912. * Modifies the mesh geometry according to a displacement map.
  28913. * 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.
  28914. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28915. * This method returns nothing.
  28916. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28917. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28918. * 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.
  28919. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28920. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28921. *
  28922. * Returns the Mesh.
  28923. */
  28924. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28925. var _this = this;
  28926. var scene = this.getScene();
  28927. var onload = function (img) {
  28928. // Getting height map data
  28929. var canvas = document.createElement("canvas");
  28930. var context = canvas.getContext("2d");
  28931. var heightMapWidth = img.width;
  28932. var heightMapHeight = img.height;
  28933. canvas.width = heightMapWidth;
  28934. canvas.height = heightMapHeight;
  28935. context.drawImage(img, 0, 0);
  28936. // Create VertexData from map data
  28937. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28938. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28939. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28940. //execute success callback, if set
  28941. if (onSuccess) {
  28942. onSuccess(_this);
  28943. }
  28944. };
  28945. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28946. return this;
  28947. };
  28948. /**
  28949. * Modifies the mesh geometry according to a displacementMap buffer.
  28950. * 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.
  28951. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28952. * This method returns nothing.
  28953. * 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.
  28954. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28955. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28956. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28957. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28958. *
  28959. * Returns the Mesh.
  28960. */
  28961. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28962. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28963. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28964. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28965. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28966. return this;
  28967. }
  28968. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28969. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28970. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28971. var position = BABYLON.Vector3.Zero();
  28972. var normal = BABYLON.Vector3.Zero();
  28973. var uv = BABYLON.Vector2.Zero();
  28974. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28975. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28976. for (var index = 0; index < positions.length; index += 3) {
  28977. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28978. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28979. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28980. // Compute height
  28981. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28982. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28983. var pos = (u + v * heightMapWidth) * 4;
  28984. var r = buffer[pos] / 255.0;
  28985. var g = buffer[pos + 1] / 255.0;
  28986. var b = buffer[pos + 2] / 255.0;
  28987. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28988. normal.normalize();
  28989. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28990. position = position.add(normal);
  28991. position.toArray(positions, index);
  28992. }
  28993. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28994. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28995. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28996. return this;
  28997. };
  28998. /**
  28999. * Modify the mesh to get a flat shading rendering.
  29000. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29001. * This method returns the Mesh.
  29002. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29003. */
  29004. Mesh.prototype.convertToFlatShadedMesh = function () {
  29005. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29006. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29007. var kinds = this.getVerticesDataKinds();
  29008. var vbs = {};
  29009. var data = {};
  29010. var newdata = {};
  29011. var updatableNormals = false;
  29012. var kindIndex;
  29013. var kind;
  29014. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29015. kind = kinds[kindIndex];
  29016. var vertexBuffer = this.getVertexBuffer(kind);
  29017. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29018. updatableNormals = vertexBuffer.isUpdatable();
  29019. kinds.splice(kindIndex, 1);
  29020. kindIndex--;
  29021. continue;
  29022. }
  29023. vbs[kind] = vertexBuffer;
  29024. data[kind] = vbs[kind].getData();
  29025. newdata[kind] = [];
  29026. }
  29027. // Save previous submeshes
  29028. var previousSubmeshes = this.subMeshes.slice(0);
  29029. var indices = this.getIndices();
  29030. var totalIndices = this.getTotalIndices();
  29031. // Generating unique vertices per face
  29032. var index;
  29033. for (index = 0; index < totalIndices; index++) {
  29034. var vertexIndex = indices[index];
  29035. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29036. kind = kinds[kindIndex];
  29037. var stride = vbs[kind].getStrideSize();
  29038. for (var offset = 0; offset < stride; offset++) {
  29039. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29040. }
  29041. }
  29042. }
  29043. // Updating faces & normal
  29044. var normals = [];
  29045. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29046. for (index = 0; index < totalIndices; index += 3) {
  29047. indices[index] = index;
  29048. indices[index + 1] = index + 1;
  29049. indices[index + 2] = index + 2;
  29050. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29051. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29052. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29053. var p1p2 = p1.subtract(p2);
  29054. var p3p2 = p3.subtract(p2);
  29055. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29056. // Store same normals for every vertex
  29057. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29058. normals.push(normal.x);
  29059. normals.push(normal.y);
  29060. normals.push(normal.z);
  29061. }
  29062. }
  29063. this.setIndices(indices);
  29064. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29065. // Updating vertex buffers
  29066. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29067. kind = kinds[kindIndex];
  29068. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29069. }
  29070. // Updating submeshes
  29071. this.releaseSubMeshes();
  29072. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29073. var previousOne = previousSubmeshes[submeshIndex];
  29074. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29075. }
  29076. this.synchronizeInstances();
  29077. return this;
  29078. };
  29079. /**
  29080. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29081. * In other words, more vertices, no more indices and a single bigger VBO.
  29082. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29083. * Returns the Mesh.
  29084. */
  29085. Mesh.prototype.convertToUnIndexedMesh = function () {
  29086. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29087. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29088. var kinds = this.getVerticesDataKinds();
  29089. var vbs = {};
  29090. var data = {};
  29091. var newdata = {};
  29092. var kindIndex;
  29093. var kind;
  29094. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29095. kind = kinds[kindIndex];
  29096. var vertexBuffer = this.getVertexBuffer(kind);
  29097. vbs[kind] = vertexBuffer;
  29098. data[kind] = vbs[kind].getData();
  29099. newdata[kind] = [];
  29100. }
  29101. // Save previous submeshes
  29102. var previousSubmeshes = this.subMeshes.slice(0);
  29103. var indices = this.getIndices();
  29104. var totalIndices = this.getTotalIndices();
  29105. // Generating unique vertices per face
  29106. var index;
  29107. for (index = 0; index < totalIndices; index++) {
  29108. var vertexIndex = indices[index];
  29109. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29110. kind = kinds[kindIndex];
  29111. var stride = vbs[kind].getStrideSize();
  29112. for (var offset = 0; offset < stride; offset++) {
  29113. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29114. }
  29115. }
  29116. }
  29117. // Updating indices
  29118. for (index = 0; index < totalIndices; index += 3) {
  29119. indices[index] = index;
  29120. indices[index + 1] = index + 1;
  29121. indices[index + 2] = index + 2;
  29122. }
  29123. this.setIndices(indices);
  29124. // Updating vertex buffers
  29125. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29126. kind = kinds[kindIndex];
  29127. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29128. }
  29129. // Updating submeshes
  29130. this.releaseSubMeshes();
  29131. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29132. var previousOne = previousSubmeshes[submeshIndex];
  29133. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29134. }
  29135. this._unIndexed = true;
  29136. this.synchronizeInstances();
  29137. return this;
  29138. };
  29139. /**
  29140. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29141. * This method returns the Mesh.
  29142. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29143. */
  29144. Mesh.prototype.flipFaces = function (flipNormals) {
  29145. if (flipNormals === void 0) { flipNormals = false; }
  29146. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29147. var i;
  29148. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29149. for (i = 0; i < vertex_data.normals.length; i++) {
  29150. vertex_data.normals[i] *= -1;
  29151. }
  29152. }
  29153. if (vertex_data.indices) {
  29154. var temp;
  29155. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29156. // reassign indices
  29157. temp = vertex_data.indices[i + 1];
  29158. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29159. vertex_data.indices[i + 2] = temp;
  29160. }
  29161. }
  29162. vertex_data.applyToMesh(this);
  29163. return this;
  29164. };
  29165. // Instances
  29166. /**
  29167. * Creates a new InstancedMesh object from the mesh model.
  29168. * An instance shares the same properties and the same material than its model.
  29169. * Only these properties of each instance can then be set individually :
  29170. * - position
  29171. * - rotation
  29172. * - rotationQuaternion
  29173. * - setPivotMatrix
  29174. * - scaling
  29175. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29176. * Warning : this method is not supported for Line mesh and LineSystem
  29177. */
  29178. Mesh.prototype.createInstance = function (name) {
  29179. return new BABYLON.InstancedMesh(name, this);
  29180. };
  29181. /**
  29182. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29183. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29184. * This method returns the Mesh.
  29185. */
  29186. Mesh.prototype.synchronizeInstances = function () {
  29187. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29188. var instance = this.instances[instanceIndex];
  29189. instance._syncSubMeshes();
  29190. }
  29191. return this;
  29192. };
  29193. /**
  29194. * Simplify the mesh according to the given array of settings.
  29195. * Function will return immediately and will simplify async. It returns the Mesh.
  29196. * @param settings a collection of simplification settings.
  29197. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29198. * @param type the type of simplification to run.
  29199. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29200. */
  29201. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29202. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29203. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29204. this.getScene().simplificationQueue.addTask({
  29205. settings: settings,
  29206. parallelProcessing: parallelProcessing,
  29207. mesh: this,
  29208. simplificationType: simplificationType,
  29209. successCallback: successCallback
  29210. });
  29211. return this;
  29212. };
  29213. /**
  29214. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29215. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29216. * This should be used together with the simplification to avoid disappearing triangles.
  29217. * Returns the Mesh.
  29218. * @param successCallback an optional success callback to be called after the optimization finished.
  29219. */
  29220. Mesh.prototype.optimizeIndices = function (successCallback) {
  29221. var _this = this;
  29222. var indices = this.getIndices();
  29223. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29224. if (!positions || !indices) {
  29225. return this;
  29226. }
  29227. var vectorPositions = new Array();
  29228. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29229. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29230. }
  29231. var dupes = new Array();
  29232. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29233. var realPos = vectorPositions.length - 1 - iteration;
  29234. var testedPosition = vectorPositions[realPos];
  29235. for (var j = 0; j < realPos; ++j) {
  29236. var againstPosition = vectorPositions[j];
  29237. if (testedPosition.equals(againstPosition)) {
  29238. dupes[realPos] = j;
  29239. break;
  29240. }
  29241. }
  29242. }, function () {
  29243. for (var i = 0; i < indices.length; ++i) {
  29244. indices[i] = dupes[indices[i]] || indices[i];
  29245. }
  29246. //indices are now reordered
  29247. var originalSubMeshes = _this.subMeshes.slice(0);
  29248. _this.setIndices(indices);
  29249. _this.subMeshes = originalSubMeshes;
  29250. if (successCallback) {
  29251. successCallback(_this);
  29252. }
  29253. });
  29254. return this;
  29255. };
  29256. Mesh.prototype.serialize = function (serializationObject) {
  29257. serializationObject.name = this.name;
  29258. serializationObject.id = this.id;
  29259. serializationObject.type = this.getClassName();
  29260. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29261. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29262. }
  29263. serializationObject.position = this.position.asArray();
  29264. if (this.rotationQuaternion) {
  29265. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29266. }
  29267. else if (this.rotation) {
  29268. serializationObject.rotation = this.rotation.asArray();
  29269. }
  29270. serializationObject.scaling = this.scaling.asArray();
  29271. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29272. serializationObject.isEnabled = this.isEnabled(false);
  29273. serializationObject.isVisible = this.isVisible;
  29274. serializationObject.infiniteDistance = this.infiniteDistance;
  29275. serializationObject.pickable = this.isPickable;
  29276. serializationObject.receiveShadows = this.receiveShadows;
  29277. serializationObject.billboardMode = this.billboardMode;
  29278. serializationObject.visibility = this.visibility;
  29279. serializationObject.checkCollisions = this.checkCollisions;
  29280. serializationObject.isBlocker = this.isBlocker;
  29281. // Parent
  29282. if (this.parent) {
  29283. serializationObject.parentId = this.parent.id;
  29284. }
  29285. // Geometry
  29286. serializationObject.isUnIndexed = this.isUnIndexed;
  29287. var geometry = this._geometry;
  29288. if (geometry) {
  29289. var geometryId = geometry.id;
  29290. serializationObject.geometryId = geometryId;
  29291. // SubMeshes
  29292. serializationObject.subMeshes = [];
  29293. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29294. var subMesh = this.subMeshes[subIndex];
  29295. serializationObject.subMeshes.push({
  29296. materialIndex: subMesh.materialIndex,
  29297. verticesStart: subMesh.verticesStart,
  29298. verticesCount: subMesh.verticesCount,
  29299. indexStart: subMesh.indexStart,
  29300. indexCount: subMesh.indexCount
  29301. });
  29302. }
  29303. }
  29304. // Material
  29305. if (this.material) {
  29306. serializationObject.materialId = this.material.id;
  29307. }
  29308. else {
  29309. this.material = null;
  29310. }
  29311. // Morph targets
  29312. if (this.morphTargetManager) {
  29313. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29314. }
  29315. // Skeleton
  29316. if (this.skeleton) {
  29317. serializationObject.skeletonId = this.skeleton.id;
  29318. }
  29319. // Physics
  29320. //TODO implement correct serialization for physics impostors.
  29321. var impostor = this.getPhysicsImpostor();
  29322. if (impostor) {
  29323. serializationObject.physicsMass = impostor.getParam("mass");
  29324. serializationObject.physicsFriction = impostor.getParam("friction");
  29325. serializationObject.physicsRestitution = impostor.getParam("mass");
  29326. serializationObject.physicsImpostor = impostor.type;
  29327. }
  29328. // Metadata
  29329. if (this.metadata) {
  29330. serializationObject.metadata = this.metadata;
  29331. }
  29332. // Instances
  29333. serializationObject.instances = [];
  29334. for (var index = 0; index < this.instances.length; index++) {
  29335. var instance = this.instances[index];
  29336. var serializationInstance = {
  29337. name: instance.name,
  29338. id: instance.id,
  29339. position: instance.position.asArray(),
  29340. scaling: instance.scaling.asArray()
  29341. };
  29342. if (instance.rotationQuaternion) {
  29343. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29344. }
  29345. else if (instance.rotation) {
  29346. serializationInstance.rotation = instance.rotation.asArray();
  29347. }
  29348. serializationObject.instances.push(serializationInstance);
  29349. // Animations
  29350. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29351. serializationInstance.ranges = instance.serializeAnimationRanges();
  29352. }
  29353. //
  29354. // Animations
  29355. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29356. serializationObject.ranges = this.serializeAnimationRanges();
  29357. // Layer mask
  29358. serializationObject.layerMask = this.layerMask;
  29359. // Alpha
  29360. serializationObject.alphaIndex = this.alphaIndex;
  29361. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29362. // Overlay
  29363. serializationObject.overlayAlpha = this.overlayAlpha;
  29364. serializationObject.overlayColor = this.overlayColor.asArray();
  29365. serializationObject.renderOverlay = this.renderOverlay;
  29366. // Fog
  29367. serializationObject.applyFog = this.applyFog;
  29368. // Action Manager
  29369. if (this.actionManager) {
  29370. serializationObject.actions = this.actionManager.serialize(this.name);
  29371. }
  29372. };
  29373. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29374. if (!this.geometry) {
  29375. return;
  29376. }
  29377. this._markSubMeshesAsAttributesDirty();
  29378. var morphTargetManager = this._morphTargetManager;
  29379. if (morphTargetManager && morphTargetManager.vertexCount) {
  29380. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29381. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29382. this.morphTargetManager = null;
  29383. return;
  29384. }
  29385. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29386. var morphTarget = morphTargetManager.getActiveTarget(index);
  29387. var positions = morphTarget.getPositions();
  29388. if (!positions) {
  29389. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29390. return;
  29391. }
  29392. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29393. var normals = morphTarget.getNormals();
  29394. if (normals) {
  29395. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29396. }
  29397. var tangents = morphTarget.getTangents();
  29398. if (tangents) {
  29399. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29400. }
  29401. }
  29402. }
  29403. else {
  29404. var index = 0;
  29405. // Positions
  29406. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29407. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29408. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29409. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29410. }
  29411. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29412. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29413. }
  29414. index++;
  29415. }
  29416. }
  29417. };
  29418. // Statics
  29419. /**
  29420. * Returns a new Mesh object parsed from the source provided.
  29421. * The parameter `parsedMesh` is the source.
  29422. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29423. */
  29424. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29425. var mesh;
  29426. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29427. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29428. }
  29429. else {
  29430. mesh = new Mesh(parsedMesh.name, scene);
  29431. }
  29432. mesh.id = parsedMesh.id;
  29433. if (BABYLON.Tags) {
  29434. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29435. }
  29436. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29437. if (parsedMesh.metadata !== undefined) {
  29438. mesh.metadata = parsedMesh.metadata;
  29439. }
  29440. if (parsedMesh.rotationQuaternion) {
  29441. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29442. }
  29443. else if (parsedMesh.rotation) {
  29444. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29445. }
  29446. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29447. if (parsedMesh.localMatrix) {
  29448. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29449. }
  29450. else if (parsedMesh.pivotMatrix) {
  29451. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29452. }
  29453. mesh.setEnabled(parsedMesh.isEnabled);
  29454. mesh.isVisible = parsedMesh.isVisible;
  29455. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29456. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29457. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29458. if (parsedMesh.applyFog !== undefined) {
  29459. mesh.applyFog = parsedMesh.applyFog;
  29460. }
  29461. if (parsedMesh.pickable !== undefined) {
  29462. mesh.isPickable = parsedMesh.pickable;
  29463. }
  29464. if (parsedMesh.alphaIndex !== undefined) {
  29465. mesh.alphaIndex = parsedMesh.alphaIndex;
  29466. }
  29467. mesh.receiveShadows = parsedMesh.receiveShadows;
  29468. mesh.billboardMode = parsedMesh.billboardMode;
  29469. if (parsedMesh.visibility !== undefined) {
  29470. mesh.visibility = parsedMesh.visibility;
  29471. }
  29472. mesh.checkCollisions = parsedMesh.checkCollisions;
  29473. if (parsedMesh.isBlocker !== undefined) {
  29474. mesh.isBlocker = parsedMesh.isBlocker;
  29475. }
  29476. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29477. // freezeWorldMatrix
  29478. if (parsedMesh.freezeWorldMatrix) {
  29479. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29480. }
  29481. // Parent
  29482. if (parsedMesh.parentId) {
  29483. mesh._waitingParentId = parsedMesh.parentId;
  29484. }
  29485. // Actions
  29486. if (parsedMesh.actions !== undefined) {
  29487. mesh._waitingActions = parsedMesh.actions;
  29488. }
  29489. // Overlay
  29490. if (parsedMesh.overlayAlpha !== undefined) {
  29491. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29492. }
  29493. if (parsedMesh.overlayColor !== undefined) {
  29494. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29495. }
  29496. if (parsedMesh.renderOverlay !== undefined) {
  29497. mesh.renderOverlay = parsedMesh.renderOverlay;
  29498. }
  29499. // Geometry
  29500. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29501. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29502. if (parsedMesh.delayLoadingFile) {
  29503. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29504. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29505. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29506. if (parsedMesh._binaryInfo) {
  29507. mesh._binaryInfo = parsedMesh._binaryInfo;
  29508. }
  29509. mesh._delayInfo = [];
  29510. if (parsedMesh.hasUVs) {
  29511. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29512. }
  29513. if (parsedMesh.hasUVs2) {
  29514. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29515. }
  29516. if (parsedMesh.hasUVs3) {
  29517. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29518. }
  29519. if (parsedMesh.hasUVs4) {
  29520. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29521. }
  29522. if (parsedMesh.hasUVs5) {
  29523. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29524. }
  29525. if (parsedMesh.hasUVs6) {
  29526. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29527. }
  29528. if (parsedMesh.hasColors) {
  29529. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29530. }
  29531. if (parsedMesh.hasMatricesIndices) {
  29532. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29533. }
  29534. if (parsedMesh.hasMatricesWeights) {
  29535. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29536. }
  29537. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29538. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29539. mesh._checkDelayState();
  29540. }
  29541. }
  29542. else {
  29543. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29544. }
  29545. // Material
  29546. if (parsedMesh.materialId) {
  29547. mesh.setMaterialByID(parsedMesh.materialId);
  29548. }
  29549. else {
  29550. mesh.material = null;
  29551. }
  29552. // Morph targets
  29553. if (parsedMesh.morphTargetManagerId > -1) {
  29554. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29555. }
  29556. // Skeleton
  29557. if (parsedMesh.skeletonId > -1) {
  29558. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29559. if (parsedMesh.numBoneInfluencers) {
  29560. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29561. }
  29562. }
  29563. // Animations
  29564. if (parsedMesh.animations) {
  29565. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29566. var parsedAnimation = parsedMesh.animations[animationIndex];
  29567. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29568. }
  29569. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29570. }
  29571. if (parsedMesh.autoAnimate) {
  29572. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29573. }
  29574. // Layer Mask
  29575. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29576. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29577. }
  29578. else {
  29579. mesh.layerMask = 0x0FFFFFFF;
  29580. }
  29581. // Physics
  29582. if (parsedMesh.physicsImpostor) {
  29583. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29584. mass: parsedMesh.physicsMass,
  29585. friction: parsedMesh.physicsFriction,
  29586. restitution: parsedMesh.physicsRestitution
  29587. }, scene);
  29588. }
  29589. // Instances
  29590. if (parsedMesh.instances) {
  29591. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29592. var parsedInstance = parsedMesh.instances[index];
  29593. var instance = mesh.createInstance(parsedInstance.name);
  29594. if (parsedInstance.id) {
  29595. instance.id = parsedInstance.id;
  29596. }
  29597. if (BABYLON.Tags) {
  29598. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29599. }
  29600. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29601. if (parsedInstance.parentId) {
  29602. instance._waitingParentId = parsedInstance.parentId;
  29603. }
  29604. if (parsedInstance.rotationQuaternion) {
  29605. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29606. }
  29607. else if (parsedInstance.rotation) {
  29608. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29609. }
  29610. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29611. instance.checkCollisions = mesh.checkCollisions;
  29612. if (parsedMesh.animations) {
  29613. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29614. parsedAnimation = parsedMesh.animations[animationIndex];
  29615. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29616. }
  29617. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29618. }
  29619. }
  29620. }
  29621. return mesh;
  29622. };
  29623. /**
  29624. * Creates a ribbon mesh.
  29625. * Please consider using the same method from the MeshBuilder class instead.
  29626. * 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.
  29627. *
  29628. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29629. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29630. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29631. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29632. * 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.
  29633. * 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.
  29634. * 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
  29635. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29636. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29638. */
  29639. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29640. if (closeArray === void 0) { closeArray = false; }
  29641. if (updatable === void 0) { updatable = false; }
  29642. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29643. pathArray: pathArray,
  29644. closeArray: closeArray,
  29645. closePath: closePath,
  29646. offset: offset,
  29647. updatable: updatable,
  29648. sideOrientation: sideOrientation,
  29649. instance: instance
  29650. }, scene);
  29651. };
  29652. /**
  29653. * Creates a plane polygonal mesh. By default, this is a disc.
  29654. * Please consider using the same method from the MeshBuilder class instead.
  29655. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29656. * 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.
  29657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29660. */
  29661. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29662. if (scene === void 0) { scene = null; }
  29663. var options = {
  29664. radius: radius,
  29665. tessellation: tessellation,
  29666. sideOrientation: sideOrientation,
  29667. updatable: updatable
  29668. };
  29669. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29670. };
  29671. /**
  29672. * Creates a box mesh.
  29673. * Please consider using the same method from the MeshBuilder class instead.
  29674. * The parameter `size` sets the size (float) of each box side (default 1).
  29675. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29676. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29677. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29678. */
  29679. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29680. if (scene === void 0) { scene = null; }
  29681. var options = {
  29682. size: size,
  29683. sideOrientation: sideOrientation,
  29684. updatable: updatable
  29685. };
  29686. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29687. };
  29688. /**
  29689. * Creates a sphere mesh.
  29690. * Please consider using the same method from the MeshBuilder class instead.
  29691. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29692. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29696. */
  29697. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29698. var options = {
  29699. segments: segments,
  29700. diameterX: diameter,
  29701. diameterY: diameter,
  29702. diameterZ: diameter,
  29703. sideOrientation: sideOrientation,
  29704. updatable: updatable
  29705. };
  29706. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29707. };
  29708. /**
  29709. * Creates a cylinder or a cone mesh.
  29710. * Please consider using the same method from the MeshBuilder class instead.
  29711. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29712. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29713. * 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.
  29714. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29715. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29716. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29717. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29718. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29719. */
  29720. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29721. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29722. if (scene !== undefined) {
  29723. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29724. updatable = scene;
  29725. }
  29726. scene = subdivisions;
  29727. subdivisions = 1;
  29728. }
  29729. var options = {
  29730. height: height,
  29731. diameterTop: diameterTop,
  29732. diameterBottom: diameterBottom,
  29733. tessellation: tessellation,
  29734. subdivisions: subdivisions,
  29735. sideOrientation: sideOrientation,
  29736. updatable: updatable
  29737. };
  29738. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29739. };
  29740. // Torus (Code from SharpDX.org)
  29741. /**
  29742. * Creates a torus mesh.
  29743. * Please consider using the same method from the MeshBuilder class instead.
  29744. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29745. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29746. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29747. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29748. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29750. */
  29751. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29752. var options = {
  29753. diameter: diameter,
  29754. thickness: thickness,
  29755. tessellation: tessellation,
  29756. sideOrientation: sideOrientation,
  29757. updatable: updatable
  29758. };
  29759. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29760. };
  29761. /**
  29762. * Creates a torus knot mesh.
  29763. * Please consider using the same method from the MeshBuilder class instead.
  29764. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29765. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29766. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29767. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29768. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29769. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29771. */
  29772. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29773. var options = {
  29774. radius: radius,
  29775. tube: tube,
  29776. radialSegments: radialSegments,
  29777. tubularSegments: tubularSegments,
  29778. p: p,
  29779. q: q,
  29780. sideOrientation: sideOrientation,
  29781. updatable: updatable
  29782. };
  29783. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29784. };
  29785. /**
  29786. * Creates a line mesh.
  29787. * Please consider using the same method from the MeshBuilder class instead.
  29788. * 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.
  29789. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29790. * The parameter `points` is an array successive Vector3.
  29791. * 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
  29792. * When updating an instance, remember that only point positions can change, not the number of points.
  29793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29794. */
  29795. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29796. if (scene === void 0) { scene = null; }
  29797. if (updatable === void 0) { updatable = false; }
  29798. if (instance === void 0) { instance = null; }
  29799. var options = {
  29800. points: points,
  29801. updatable: updatable,
  29802. instance: instance
  29803. };
  29804. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29805. };
  29806. /**
  29807. * Creates a dashed line mesh.
  29808. * Please consider using the same method from the MeshBuilder class instead.
  29809. * 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.
  29810. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29811. * The parameter `points` is an array successive Vector3.
  29812. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29813. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29814. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29815. * 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
  29816. * When updating an instance, remember that only point positions can change, not the number of points.
  29817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29818. */
  29819. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29820. if (scene === void 0) { scene = null; }
  29821. var options = {
  29822. points: points,
  29823. dashSize: dashSize,
  29824. gapSize: gapSize,
  29825. dashNb: dashNb,
  29826. updatable: updatable,
  29827. instance: instance
  29828. };
  29829. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29830. };
  29831. /**
  29832. * Creates a polygon mesh.
  29833. * Please consider using the same method from the MeshBuilder class instead.
  29834. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29835. * 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.
  29836. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29837. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29838. * Remember you can only change the shape positions, not their number when updating a polygon.
  29839. */
  29840. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29841. var options = {
  29842. shape: shape,
  29843. holes: holes,
  29844. updatable: updatable,
  29845. sideOrientation: sideOrientation
  29846. };
  29847. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29848. };
  29849. /**
  29850. * Creates an extruded polygon mesh, with depth in the Y direction.
  29851. * Please consider using the same method from the MeshBuilder class instead.
  29852. */
  29853. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29854. var options = {
  29855. shape: shape,
  29856. holes: holes,
  29857. depth: depth,
  29858. updatable: updatable,
  29859. sideOrientation: sideOrientation
  29860. };
  29861. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29862. };
  29863. /**
  29864. * Creates an extruded shape mesh.
  29865. * 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.
  29866. * Please consider using the same method from the MeshBuilder class instead.
  29867. *
  29868. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29869. * 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
  29870. * extruded along the Z axis.
  29871. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29872. * 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.
  29873. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29874. * 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
  29875. * 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
  29876. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29877. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29878. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29879. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29880. */
  29881. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29882. if (scene === void 0) { scene = null; }
  29883. var options = {
  29884. shape: shape,
  29885. path: path,
  29886. scale: scale,
  29887. rotation: rotation,
  29888. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29889. sideOrientation: sideOrientation,
  29890. instance: instance,
  29891. updatable: updatable
  29892. };
  29893. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29894. };
  29895. /**
  29896. * Creates an custom extruded shape mesh.
  29897. * 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.
  29898. * Please consider using the same method from the MeshBuilder class instead.
  29899. *
  29900. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29901. * 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
  29902. * extruded along the Z axis.
  29903. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29904. * 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
  29905. * and the distance of this point from the begining of the path :
  29906. * ```javascript
  29907. * var rotationFunction = function(i, distance) {
  29908. * // do things
  29909. * return rotationValue; }
  29910. * ```
  29911. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29912. * 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
  29913. * and the distance of this point from the begining of the path :
  29914. * ```javascript
  29915. * var scaleFunction = function(i, distance) {
  29916. * // do things
  29917. * return scaleValue;}
  29918. * ```
  29919. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29920. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29921. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29922. * 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
  29923. * 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
  29924. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29925. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29928. */
  29929. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29930. var options = {
  29931. shape: shape,
  29932. path: path,
  29933. scaleFunction: scaleFunction,
  29934. rotationFunction: rotationFunction,
  29935. ribbonCloseArray: ribbonCloseArray,
  29936. ribbonClosePath: ribbonClosePath,
  29937. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29938. sideOrientation: sideOrientation,
  29939. instance: instance,
  29940. updatable: updatable
  29941. };
  29942. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29943. };
  29944. /**
  29945. * Creates lathe mesh.
  29946. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29947. * Please consider using the same method from the MeshBuilder class instead.
  29948. * 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
  29949. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29950. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29951. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29952. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29953. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29955. */
  29956. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29957. var options = {
  29958. shape: shape,
  29959. radius: radius,
  29960. tessellation: tessellation,
  29961. sideOrientation: sideOrientation,
  29962. updatable: updatable
  29963. };
  29964. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29965. };
  29966. /**
  29967. * Creates a plane mesh.
  29968. * Please consider using the same method from the MeshBuilder class instead.
  29969. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29973. */
  29974. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29975. var options = {
  29976. size: size,
  29977. width: size,
  29978. height: size,
  29979. sideOrientation: sideOrientation,
  29980. updatable: updatable
  29981. };
  29982. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29983. };
  29984. /**
  29985. * Creates a ground mesh.
  29986. * Please consider using the same method from the MeshBuilder class instead.
  29987. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29988. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29990. */
  29991. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29992. var options = {
  29993. width: width,
  29994. height: height,
  29995. subdivisions: subdivisions,
  29996. updatable: updatable
  29997. };
  29998. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29999. };
  30000. /**
  30001. * Creates a tiled ground mesh.
  30002. * Please consider using the same method from the MeshBuilder class instead.
  30003. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30004. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30005. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30006. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30007. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30008. * numbers of subdivisions on the ground width and height of each tile.
  30009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30010. */
  30011. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30012. var options = {
  30013. xmin: xmin,
  30014. zmin: zmin,
  30015. xmax: xmax,
  30016. zmax: zmax,
  30017. subdivisions: subdivisions,
  30018. precision: precision,
  30019. updatable: updatable
  30020. };
  30021. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30022. };
  30023. /**
  30024. * Creates a ground mesh from a height map.
  30025. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30026. * Please consider using the same method from the MeshBuilder class instead.
  30027. * The parameter `url` sets the URL of the height map image resource.
  30028. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30029. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30030. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30031. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30032. * 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).
  30033. * This function is passed the newly built mesh :
  30034. * ```javascript
  30035. * function(mesh) { // do things
  30036. * return; }
  30037. * ```
  30038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30039. */
  30040. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30041. var options = {
  30042. width: width,
  30043. height: height,
  30044. subdivisions: subdivisions,
  30045. minHeight: minHeight,
  30046. maxHeight: maxHeight,
  30047. updatable: updatable,
  30048. onReady: onReady
  30049. };
  30050. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30051. };
  30052. /**
  30053. * Creates a tube mesh.
  30054. * 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.
  30055. * Please consider using the same method from the MeshBuilder class instead.
  30056. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30057. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30058. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30059. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30060. * 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.
  30061. * It must return a radius value (positive float) :
  30062. * ```javascript
  30063. * var radiusFunction = function(i, distance) {
  30064. * // do things
  30065. * return radius; }
  30066. * ```
  30067. * 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
  30068. * 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
  30069. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30072. */
  30073. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30074. var options = {
  30075. path: path,
  30076. radius: radius,
  30077. tessellation: tessellation,
  30078. radiusFunction: radiusFunction,
  30079. arc: 1,
  30080. cap: cap,
  30081. updatable: updatable,
  30082. sideOrientation: sideOrientation,
  30083. instance: instance
  30084. };
  30085. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30086. };
  30087. /**
  30088. * Creates a polyhedron mesh.
  30089. * Please consider using the same method from the MeshBuilder class instead.
  30090. * 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
  30091. * to choose the wanted type.
  30092. * The parameter `size` (positive float, default 1) sets the polygon size.
  30093. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30094. * 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`.
  30095. * 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
  30096. * 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)`).
  30097. * 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
  30098. * 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.
  30099. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30100. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30102. */
  30103. Mesh.CreatePolyhedron = function (name, options, scene) {
  30104. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30105. };
  30106. /**
  30107. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30108. * Please consider using the same method from the MeshBuilder class instead.
  30109. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30110. * 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`).
  30111. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30112. * 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.
  30113. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30114. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30115. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30116. */
  30117. Mesh.CreateIcoSphere = function (name, options, scene) {
  30118. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30119. };
  30120. /**
  30121. * Creates a decal mesh.
  30122. * Please consider using the same method from the MeshBuilder class instead.
  30123. * 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.
  30124. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30125. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30126. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30127. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30128. */
  30129. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30130. var options = {
  30131. position: position,
  30132. normal: normal,
  30133. size: size,
  30134. angle: angle
  30135. };
  30136. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30137. };
  30138. // Skeletons
  30139. /**
  30140. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30141. */
  30142. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30143. if (!this._sourcePositions) {
  30144. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30145. if (!source) {
  30146. return this._sourcePositions;
  30147. }
  30148. this._sourcePositions = new Float32Array(source);
  30149. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30150. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30151. }
  30152. }
  30153. return this._sourcePositions;
  30154. };
  30155. /**
  30156. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30157. */
  30158. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30159. if (!this._sourceNormals) {
  30160. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30161. if (!source) {
  30162. return this._sourceNormals;
  30163. }
  30164. this._sourceNormals = new Float32Array(source);
  30165. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30166. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30167. }
  30168. }
  30169. return this._sourceNormals;
  30170. };
  30171. /**
  30172. * Updates the vertex buffer by applying transformation from the bones.
  30173. * Returns the Mesh.
  30174. *
  30175. * @param {skeleton} skeleton to apply
  30176. */
  30177. Mesh.prototype.applySkeleton = function (skeleton) {
  30178. if (!this.geometry) {
  30179. return this;
  30180. }
  30181. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30182. return this;
  30183. }
  30184. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30185. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30186. return this;
  30187. }
  30188. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30189. return this;
  30190. }
  30191. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30192. return this;
  30193. }
  30194. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30195. return this;
  30196. }
  30197. if (!this._sourcePositions) {
  30198. var submeshes = this.subMeshes.slice();
  30199. this.setPositionsForCPUSkinning();
  30200. this.subMeshes = submeshes;
  30201. }
  30202. if (!this._sourceNormals) {
  30203. this.setNormalsForCPUSkinning();
  30204. }
  30205. // positionsData checks for not being Float32Array will only pass at most once
  30206. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30207. if (!positionsData) {
  30208. return this;
  30209. }
  30210. if (!(positionsData instanceof Float32Array)) {
  30211. positionsData = new Float32Array(positionsData);
  30212. }
  30213. // normalsData checks for not being Float32Array will only pass at most once
  30214. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30215. if (!normalsData) {
  30216. return this;
  30217. }
  30218. if (!(normalsData instanceof Float32Array)) {
  30219. normalsData = new Float32Array(normalsData);
  30220. }
  30221. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30222. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30223. if (!matricesWeightsData || !matricesIndicesData) {
  30224. return this;
  30225. }
  30226. var needExtras = this.numBoneInfluencers > 4;
  30227. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30228. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30229. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30230. var tempVector3 = BABYLON.Vector3.Zero();
  30231. var finalMatrix = new BABYLON.Matrix();
  30232. var tempMatrix = new BABYLON.Matrix();
  30233. var matWeightIdx = 0;
  30234. var inf;
  30235. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30236. var weight;
  30237. for (inf = 0; inf < 4; inf++) {
  30238. weight = matricesWeightsData[matWeightIdx + inf];
  30239. if (weight > 0) {
  30240. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30241. finalMatrix.addToSelf(tempMatrix);
  30242. }
  30243. else
  30244. break;
  30245. }
  30246. if (needExtras) {
  30247. for (inf = 0; inf < 4; inf++) {
  30248. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30249. if (weight > 0) {
  30250. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30251. finalMatrix.addToSelf(tempMatrix);
  30252. }
  30253. else
  30254. break;
  30255. }
  30256. }
  30257. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30258. tempVector3.toArray(positionsData, index);
  30259. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30260. tempVector3.toArray(normalsData, index);
  30261. finalMatrix.reset();
  30262. }
  30263. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30264. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30265. return this;
  30266. };
  30267. // Tools
  30268. /**
  30269. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30270. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30271. */
  30272. Mesh.MinMax = function (meshes) {
  30273. var minVector = null;
  30274. var maxVector = null;
  30275. meshes.forEach(function (mesh, index, array) {
  30276. var boundingInfo = mesh.getBoundingInfo();
  30277. var boundingBox = boundingInfo.boundingBox;
  30278. if (!minVector || !maxVector) {
  30279. minVector = boundingBox.minimumWorld;
  30280. maxVector = boundingBox.maximumWorld;
  30281. }
  30282. else {
  30283. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30284. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30285. }
  30286. });
  30287. if (!minVector || !maxVector) {
  30288. return {
  30289. min: BABYLON.Vector3.Zero(),
  30290. max: BABYLON.Vector3.Zero()
  30291. };
  30292. }
  30293. return {
  30294. min: minVector,
  30295. max: maxVector
  30296. };
  30297. };
  30298. /**
  30299. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30300. */
  30301. Mesh.Center = function (meshesOrMinMaxVector) {
  30302. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30303. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30304. };
  30305. /**
  30306. * Merge the array of meshes into a single mesh for performance reasons.
  30307. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30308. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30309. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30310. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30311. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30312. */
  30313. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30314. if (disposeSource === void 0) { disposeSource = true; }
  30315. var index;
  30316. if (!allow32BitsIndices) {
  30317. var totalVertices = 0;
  30318. // Counting vertices
  30319. for (index = 0; index < meshes.length; index++) {
  30320. if (meshes[index]) {
  30321. totalVertices += meshes[index].getTotalVertices();
  30322. if (totalVertices > 65536) {
  30323. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30324. return null;
  30325. }
  30326. }
  30327. }
  30328. }
  30329. // Merge
  30330. var vertexData = null;
  30331. var otherVertexData;
  30332. var indiceArray = new Array();
  30333. var source = null;
  30334. for (index = 0; index < meshes.length; index++) {
  30335. if (meshes[index]) {
  30336. meshes[index].computeWorldMatrix(true);
  30337. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30338. otherVertexData.transform(meshes[index].getWorldMatrix());
  30339. if (vertexData) {
  30340. vertexData.merge(otherVertexData);
  30341. }
  30342. else {
  30343. vertexData = otherVertexData;
  30344. source = meshes[index];
  30345. }
  30346. if (subdivideWithSubMeshes) {
  30347. indiceArray.push(meshes[index].getTotalIndices());
  30348. }
  30349. }
  30350. }
  30351. source = source;
  30352. if (!meshSubclass) {
  30353. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30354. }
  30355. vertexData.applyToMesh(meshSubclass);
  30356. // Setting properties
  30357. meshSubclass.material = source.material;
  30358. meshSubclass.checkCollisions = source.checkCollisions;
  30359. // Cleaning
  30360. if (disposeSource) {
  30361. for (index = 0; index < meshes.length; index++) {
  30362. if (meshes[index]) {
  30363. meshes[index].dispose();
  30364. }
  30365. }
  30366. }
  30367. // Subdivide
  30368. if (subdivideWithSubMeshes) {
  30369. //-- Suppresions du submesh global
  30370. meshSubclass.releaseSubMeshes();
  30371. index = 0;
  30372. var offset = 0;
  30373. //-- aplique la subdivision en fonction du tableau d'indices
  30374. while (index < indiceArray.length) {
  30375. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30376. offset += indiceArray[index];
  30377. index++;
  30378. }
  30379. }
  30380. return meshSubclass;
  30381. };
  30382. // Consts
  30383. Mesh._FRONTSIDE = 0;
  30384. Mesh._BACKSIDE = 1;
  30385. Mesh._DOUBLESIDE = 2;
  30386. Mesh._DEFAULTSIDE = 0;
  30387. Mesh._NO_CAP = 0;
  30388. Mesh._CAP_START = 1;
  30389. Mesh._CAP_END = 2;
  30390. Mesh._CAP_ALL = 3;
  30391. return Mesh;
  30392. }(BABYLON.AbstractMesh));
  30393. BABYLON.Mesh = Mesh;
  30394. })(BABYLON || (BABYLON = {}));
  30395. //# sourceMappingURL=babylon.mesh.js.map
  30396. var BABYLON;
  30397. (function (BABYLON) {
  30398. var BaseSubMesh = /** @class */ (function () {
  30399. function BaseSubMesh() {
  30400. }
  30401. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30402. get: function () {
  30403. return this._materialEffect;
  30404. },
  30405. enumerable: true,
  30406. configurable: true
  30407. });
  30408. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30409. if (defines === void 0) { defines = null; }
  30410. if (this._materialEffect === effect) {
  30411. if (!effect) {
  30412. this._materialDefines = null;
  30413. }
  30414. return;
  30415. }
  30416. this._materialDefines = defines;
  30417. this._materialEffect = effect;
  30418. };
  30419. return BaseSubMesh;
  30420. }());
  30421. BABYLON.BaseSubMesh = BaseSubMesh;
  30422. var SubMesh = /** @class */ (function (_super) {
  30423. __extends(SubMesh, _super);
  30424. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30425. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30426. var _this = _super.call(this) || this;
  30427. _this.materialIndex = materialIndex;
  30428. _this.verticesStart = verticesStart;
  30429. _this.verticesCount = verticesCount;
  30430. _this.indexStart = indexStart;
  30431. _this.indexCount = indexCount;
  30432. _this._renderId = 0;
  30433. _this._mesh = mesh;
  30434. _this._renderingMesh = renderingMesh || mesh;
  30435. mesh.subMeshes.push(_this);
  30436. _this._trianglePlanes = [];
  30437. _this._id = mesh.subMeshes.length - 1;
  30438. if (createBoundingBox) {
  30439. _this.refreshBoundingInfo();
  30440. mesh.computeWorldMatrix(true);
  30441. }
  30442. return _this;
  30443. }
  30444. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30445. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30446. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30447. };
  30448. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30449. get: function () {
  30450. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30451. },
  30452. enumerable: true,
  30453. configurable: true
  30454. });
  30455. /**
  30456. * Returns the submesh BoudingInfo object.
  30457. */
  30458. SubMesh.prototype.getBoundingInfo = function () {
  30459. if (this.IsGlobal) {
  30460. return this._mesh.getBoundingInfo();
  30461. }
  30462. return this._boundingInfo;
  30463. };
  30464. /**
  30465. * Sets the submesh BoundingInfo.
  30466. * Return the SubMesh.
  30467. */
  30468. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30469. this._boundingInfo = boundingInfo;
  30470. return this;
  30471. };
  30472. /**
  30473. * Returns the mesh of the current submesh.
  30474. */
  30475. SubMesh.prototype.getMesh = function () {
  30476. return this._mesh;
  30477. };
  30478. /**
  30479. * Returns the rendering mesh of the submesh.
  30480. */
  30481. SubMesh.prototype.getRenderingMesh = function () {
  30482. return this._renderingMesh;
  30483. };
  30484. /**
  30485. * Returns the submesh material.
  30486. */
  30487. SubMesh.prototype.getMaterial = function () {
  30488. var rootMaterial = this._renderingMesh.material;
  30489. if (rootMaterial === null || rootMaterial === undefined) {
  30490. return this._mesh.getScene().defaultMaterial;
  30491. }
  30492. else if (rootMaterial.getSubMaterial) {
  30493. var multiMaterial = rootMaterial;
  30494. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30495. if (this._currentMaterial !== effectiveMaterial) {
  30496. this._currentMaterial = effectiveMaterial;
  30497. this._materialDefines = null;
  30498. }
  30499. return effectiveMaterial;
  30500. }
  30501. return rootMaterial;
  30502. };
  30503. // Methods
  30504. /**
  30505. * Sets a new updated BoundingInfo object to the submesh.
  30506. * Returns the SubMesh.
  30507. */
  30508. SubMesh.prototype.refreshBoundingInfo = function () {
  30509. this._lastColliderWorldVertices = null;
  30510. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30511. return this;
  30512. }
  30513. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30514. if (!data) {
  30515. this._boundingInfo = this._mesh.getBoundingInfo();
  30516. return this;
  30517. }
  30518. var indices = this._renderingMesh.getIndices();
  30519. var extend;
  30520. //is this the only submesh?
  30521. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30522. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30523. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30524. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30525. }
  30526. else {
  30527. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30528. }
  30529. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30530. return this;
  30531. };
  30532. SubMesh.prototype._checkCollision = function (collider) {
  30533. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30534. return boundingInfo._checkCollision(collider);
  30535. };
  30536. /**
  30537. * Updates the submesh BoundingInfo.
  30538. * Returns the Submesh.
  30539. */
  30540. SubMesh.prototype.updateBoundingInfo = function (world) {
  30541. var boundingInfo = this.getBoundingInfo();
  30542. if (!boundingInfo) {
  30543. this.refreshBoundingInfo();
  30544. boundingInfo = this.getBoundingInfo();
  30545. }
  30546. boundingInfo.update(world);
  30547. return this;
  30548. };
  30549. /**
  30550. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30551. * Boolean returned.
  30552. */
  30553. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30554. var boundingInfo = this.getBoundingInfo();
  30555. if (!boundingInfo) {
  30556. return false;
  30557. }
  30558. return boundingInfo.isInFrustum(frustumPlanes);
  30559. };
  30560. /**
  30561. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30562. * Boolean returned.
  30563. */
  30564. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30565. var boundingInfo = this.getBoundingInfo();
  30566. if (!boundingInfo) {
  30567. return false;
  30568. }
  30569. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30570. };
  30571. /**
  30572. * Renders the submesh.
  30573. * Returns it.
  30574. */
  30575. SubMesh.prototype.render = function (enableAlphaMode) {
  30576. this._renderingMesh.render(this, enableAlphaMode);
  30577. return this;
  30578. };
  30579. /**
  30580. * Returns a new Index Buffer.
  30581. * Type returned : WebGLBuffer.
  30582. */
  30583. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30584. if (!this._linesIndexBuffer) {
  30585. var linesIndices = [];
  30586. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30587. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30588. }
  30589. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30590. this.linesIndexCount = linesIndices.length;
  30591. }
  30592. return this._linesIndexBuffer;
  30593. };
  30594. /**
  30595. * True is the passed Ray intersects the submesh bounding box.
  30596. * Boolean returned.
  30597. */
  30598. SubMesh.prototype.canIntersects = function (ray) {
  30599. var boundingInfo = this.getBoundingInfo();
  30600. if (!boundingInfo) {
  30601. return false;
  30602. }
  30603. return ray.intersectsBox(boundingInfo.boundingBox);
  30604. };
  30605. /**
  30606. * Returns an object IntersectionInfo.
  30607. */
  30608. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30609. var intersectInfo = null;
  30610. // LineMesh first as it's also a Mesh...
  30611. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30612. var lineMesh = this._mesh;
  30613. // Line test
  30614. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30615. var p0 = positions[indices[index]];
  30616. var p1 = positions[indices[index + 1]];
  30617. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30618. if (length < 0) {
  30619. continue;
  30620. }
  30621. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30622. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30623. if (fastCheck) {
  30624. break;
  30625. }
  30626. }
  30627. }
  30628. }
  30629. else {
  30630. // Triangles test
  30631. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30632. var p0 = positions[indices[index]];
  30633. var p1 = positions[indices[index + 1]];
  30634. var p2 = positions[indices[index + 2]];
  30635. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30636. if (currentIntersectInfo) {
  30637. if (currentIntersectInfo.distance < 0) {
  30638. continue;
  30639. }
  30640. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30641. intersectInfo = currentIntersectInfo;
  30642. intersectInfo.faceId = index / 3;
  30643. if (fastCheck) {
  30644. break;
  30645. }
  30646. }
  30647. }
  30648. }
  30649. }
  30650. return intersectInfo;
  30651. };
  30652. SubMesh.prototype._rebuild = function () {
  30653. if (this._linesIndexBuffer) {
  30654. this._linesIndexBuffer = null;
  30655. }
  30656. };
  30657. // Clone
  30658. /**
  30659. * Creates a new Submesh from the passed Mesh.
  30660. */
  30661. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30662. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30663. if (!this.IsGlobal) {
  30664. var boundingInfo = this.getBoundingInfo();
  30665. if (!boundingInfo) {
  30666. return result;
  30667. }
  30668. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30669. }
  30670. return result;
  30671. };
  30672. // Dispose
  30673. /**
  30674. * Disposes the Submesh.
  30675. * Returns nothing.
  30676. */
  30677. SubMesh.prototype.dispose = function () {
  30678. if (this._linesIndexBuffer) {
  30679. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30680. this._linesIndexBuffer = null;
  30681. }
  30682. // Remove from mesh
  30683. var index = this._mesh.subMeshes.indexOf(this);
  30684. this._mesh.subMeshes.splice(index, 1);
  30685. };
  30686. // Statics
  30687. /**
  30688. * Creates a new Submesh from the passed parameters :
  30689. * - materialIndex (integer) : the index of the main mesh material.
  30690. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30691. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30692. * - mesh (Mesh) : the main mesh to create the submesh from.
  30693. * - renderingMesh (optional Mesh) : rendering mesh.
  30694. */
  30695. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30696. var minVertexIndex = Number.MAX_VALUE;
  30697. var maxVertexIndex = -Number.MAX_VALUE;
  30698. renderingMesh = (renderingMesh || mesh);
  30699. var indices = renderingMesh.getIndices();
  30700. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30701. var vertexIndex = indices[index];
  30702. if (vertexIndex < minVertexIndex)
  30703. minVertexIndex = vertexIndex;
  30704. if (vertexIndex > maxVertexIndex)
  30705. maxVertexIndex = vertexIndex;
  30706. }
  30707. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30708. };
  30709. return SubMesh;
  30710. }(BaseSubMesh));
  30711. BABYLON.SubMesh = SubMesh;
  30712. })(BABYLON || (BABYLON = {}));
  30713. //# sourceMappingURL=babylon.subMesh.js.map
  30714. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30715. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30716. s = arguments[i];
  30717. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30718. t[p] = s[p];
  30719. }
  30720. return t;
  30721. };
  30722. var BABYLON;
  30723. (function (BABYLON) {
  30724. /**
  30725. * Manages the defines for the Material.
  30726. */
  30727. var MaterialDefines = /** @class */ (function () {
  30728. function MaterialDefines() {
  30729. this._isDirty = true;
  30730. this._areLightsDirty = true;
  30731. this._areAttributesDirty = true;
  30732. this._areTexturesDirty = true;
  30733. this._areFresnelDirty = true;
  30734. this._areMiscDirty = true;
  30735. this._areImageProcessingDirty = true;
  30736. this._normals = false;
  30737. this._uvs = false;
  30738. this._needNormals = false;
  30739. this._needUVs = false;
  30740. }
  30741. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30742. /**
  30743. * Specifies if the material needs to be re-calculated.
  30744. */
  30745. get: function () {
  30746. return this._isDirty;
  30747. },
  30748. enumerable: true,
  30749. configurable: true
  30750. });
  30751. /**
  30752. * Marks the material to indicate that it has been re-calculated.
  30753. */
  30754. MaterialDefines.prototype.markAsProcessed = function () {
  30755. this._isDirty = false;
  30756. this._areAttributesDirty = false;
  30757. this._areTexturesDirty = false;
  30758. this._areFresnelDirty = false;
  30759. this._areLightsDirty = false;
  30760. this._areMiscDirty = false;
  30761. this._areImageProcessingDirty = false;
  30762. };
  30763. /**
  30764. * Marks the material to indicate that it needs to be re-calculated.
  30765. */
  30766. MaterialDefines.prototype.markAsUnprocessed = function () {
  30767. this._isDirty = true;
  30768. };
  30769. /**
  30770. * Marks the material to indicate all of its defines need to be re-calculated.
  30771. */
  30772. MaterialDefines.prototype.markAllAsDirty = function () {
  30773. this._areTexturesDirty = true;
  30774. this._areAttributesDirty = true;
  30775. this._areLightsDirty = true;
  30776. this._areFresnelDirty = true;
  30777. this._areMiscDirty = true;
  30778. this._areImageProcessingDirty = true;
  30779. this._isDirty = true;
  30780. };
  30781. /**
  30782. * Marks the material to indicate that image processing needs to be re-calculated.
  30783. */
  30784. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30785. this._areImageProcessingDirty = true;
  30786. this._isDirty = true;
  30787. };
  30788. /**
  30789. * Marks the material to indicate the lights need to be re-calculated.
  30790. */
  30791. MaterialDefines.prototype.markAsLightDirty = function () {
  30792. this._areLightsDirty = true;
  30793. this._isDirty = true;
  30794. };
  30795. /**
  30796. * Marks the attribute state as changed.
  30797. */
  30798. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30799. this._areAttributesDirty = true;
  30800. this._isDirty = true;
  30801. };
  30802. /**
  30803. * Marks the texture state as changed.
  30804. */
  30805. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30806. this._areTexturesDirty = true;
  30807. this._isDirty = true;
  30808. };
  30809. /**
  30810. * Marks the fresnel state as changed.
  30811. */
  30812. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30813. this._areFresnelDirty = true;
  30814. this._isDirty = true;
  30815. };
  30816. /**
  30817. * Marks the misc state as changed.
  30818. */
  30819. MaterialDefines.prototype.markAsMiscDirty = function () {
  30820. this._areMiscDirty = true;
  30821. this._isDirty = true;
  30822. };
  30823. /**
  30824. * Rebuilds the material defines.
  30825. */
  30826. MaterialDefines.prototype.rebuild = function () {
  30827. if (this._keys) {
  30828. delete this._keys;
  30829. }
  30830. this._keys = [];
  30831. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30832. var key = _a[_i];
  30833. if (key[0] === "_") {
  30834. continue;
  30835. }
  30836. this._keys.push(key);
  30837. }
  30838. };
  30839. /**
  30840. * Specifies if two material defines are equal.
  30841. * @param other - A material define instance to compare to.
  30842. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30843. */
  30844. MaterialDefines.prototype.isEqual = function (other) {
  30845. if (this._keys.length !== other._keys.length) {
  30846. return false;
  30847. }
  30848. for (var index = 0; index < this._keys.length; index++) {
  30849. var prop = this._keys[index];
  30850. if (this[prop] !== other[prop]) {
  30851. return false;
  30852. }
  30853. }
  30854. return true;
  30855. };
  30856. /**
  30857. * Clones this instance's defines to another instance.
  30858. * @param other - material defines to clone values to.
  30859. */
  30860. MaterialDefines.prototype.cloneTo = function (other) {
  30861. if (this._keys.length !== other._keys.length) {
  30862. other._keys = this._keys.slice(0);
  30863. }
  30864. for (var index = 0; index < this._keys.length; index++) {
  30865. var prop = this._keys[index];
  30866. other[prop] = this[prop];
  30867. }
  30868. };
  30869. /**
  30870. * Resets the material define values.
  30871. */
  30872. MaterialDefines.prototype.reset = function () {
  30873. for (var index = 0; index < this._keys.length; index++) {
  30874. var prop = this._keys[index];
  30875. if (typeof (this[prop]) === "number") {
  30876. this[prop] = 0;
  30877. }
  30878. else {
  30879. this[prop] = false;
  30880. }
  30881. }
  30882. };
  30883. /**
  30884. * Converts the material define values to a string.
  30885. * @returns - String of material define information.
  30886. */
  30887. MaterialDefines.prototype.toString = function () {
  30888. var result = "";
  30889. for (var index = 0; index < this._keys.length; index++) {
  30890. var prop = this._keys[index];
  30891. var value = this[prop];
  30892. if (typeof (value) === "number") {
  30893. result += "#define " + prop + " " + this[prop] + "\n";
  30894. }
  30895. else if (value) {
  30896. result += "#define " + prop + "\n";
  30897. }
  30898. }
  30899. return result;
  30900. };
  30901. return MaterialDefines;
  30902. }());
  30903. BABYLON.MaterialDefines = MaterialDefines;
  30904. /**
  30905. * This offers the main features of a material in BJS.
  30906. */
  30907. var Material = /** @class */ (function () {
  30908. /**
  30909. * Creates a material instance.
  30910. * @param name - The name of the material.
  30911. * @param scene - The BJS scene to reference.
  30912. * @param doNotAdd - Specifies if the material should be added to the scene.
  30913. */
  30914. function Material(name, scene, doNotAdd) {
  30915. /**
  30916. * Specifies if the ready state should be checked on each call.
  30917. */
  30918. this.checkReadyOnEveryCall = false;
  30919. /**
  30920. * Specifies if the ready state should be checked once.
  30921. */
  30922. this.checkReadyOnlyOnce = false;
  30923. /**
  30924. * The state of the material.
  30925. */
  30926. this.state = "";
  30927. /**
  30928. * The alpha value of the material.
  30929. */
  30930. this._alpha = 1.0;
  30931. /**
  30932. * Specifies if back face culling is enabled.
  30933. */
  30934. this._backFaceCulling = true;
  30935. /**
  30936. * Specifies if the material should be serialized.
  30937. */
  30938. this.doNotSerialize = false;
  30939. /**
  30940. * Specifies if the effect should be stored on sub meshes.
  30941. */
  30942. this.storeEffectOnSubMeshes = false;
  30943. /**
  30944. * An event triggered when the material is disposed.
  30945. * @type {BABYLON.Observable}
  30946. */
  30947. this.onDisposeObservable = new BABYLON.Observable();
  30948. /**
  30949. * An event triggered when the material is bound.
  30950. * @type {BABYLON.Observable}
  30951. */
  30952. this.onBindObservable = new BABYLON.Observable();
  30953. /**
  30954. * An event triggered when the material is unbound.
  30955. * @type {BABYLON.Observable}
  30956. */
  30957. this.onUnBindObservable = new BABYLON.Observable();
  30958. /**
  30959. * Stores the value of the alpha mode.
  30960. */
  30961. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30962. /**
  30963. * Stores the state of the need depth pre-pass value.
  30964. */
  30965. this._needDepthPrePass = false;
  30966. /**
  30967. * Specifies if depth writing should be disabled.
  30968. */
  30969. this.disableDepthWrite = false;
  30970. /**
  30971. * Specifies if depth writing should be forced.
  30972. */
  30973. this.forceDepthWrite = false;
  30974. /**
  30975. * Specifies if there should be a separate pass for culling.
  30976. */
  30977. this.separateCullingPass = false;
  30978. /**
  30979. * Stores the state specifing if fog should be enabled.
  30980. */
  30981. this._fogEnabled = true;
  30982. /**
  30983. * Stores the size of points.
  30984. */
  30985. this.pointSize = 1.0;
  30986. /**
  30987. * Stores the z offset value.
  30988. */
  30989. this.zOffset = 0;
  30990. /**
  30991. * Specifies if the material was previously ready.
  30992. */
  30993. this._wasPreviouslyReady = false;
  30994. /**
  30995. * Stores the fill mode state.
  30996. */
  30997. this._fillMode = Material.TriangleFillMode;
  30998. this.name = name;
  30999. this.id = name || BABYLON.Tools.RandomId();
  31000. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31001. if (this._scene.useRightHandedSystem) {
  31002. this.sideOrientation = Material.ClockWiseSideOrientation;
  31003. }
  31004. else {
  31005. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31006. }
  31007. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31008. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31009. if (!doNotAdd) {
  31010. this._scene.materials.push(this);
  31011. }
  31012. }
  31013. Object.defineProperty(Material, "TriangleFillMode", {
  31014. /**
  31015. * Returns the triangle fill mode.
  31016. */
  31017. get: function () {
  31018. return Material._TriangleFillMode;
  31019. },
  31020. enumerable: true,
  31021. configurable: true
  31022. });
  31023. Object.defineProperty(Material, "WireFrameFillMode", {
  31024. /**
  31025. * Returns the wireframe mode.
  31026. */
  31027. get: function () {
  31028. return Material._WireFrameFillMode;
  31029. },
  31030. enumerable: true,
  31031. configurable: true
  31032. });
  31033. Object.defineProperty(Material, "PointFillMode", {
  31034. /**
  31035. * Returns the point fill mode.
  31036. */
  31037. get: function () {
  31038. return Material._PointFillMode;
  31039. },
  31040. enumerable: true,
  31041. configurable: true
  31042. });
  31043. Object.defineProperty(Material, "PointListDrawMode", {
  31044. /**
  31045. * Returns the point list draw mode.
  31046. */
  31047. get: function () {
  31048. return Material._PointListDrawMode;
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. Object.defineProperty(Material, "LineListDrawMode", {
  31054. /**
  31055. * Returns the line list draw mode.
  31056. */
  31057. get: function () {
  31058. return Material._LineListDrawMode;
  31059. },
  31060. enumerable: true,
  31061. configurable: true
  31062. });
  31063. Object.defineProperty(Material, "LineLoopDrawMode", {
  31064. /**
  31065. * Returns the line loop draw mode.
  31066. */
  31067. get: function () {
  31068. return Material._LineLoopDrawMode;
  31069. },
  31070. enumerable: true,
  31071. configurable: true
  31072. });
  31073. Object.defineProperty(Material, "LineStripDrawMode", {
  31074. /**
  31075. * Returns the line strip draw mode.
  31076. */
  31077. get: function () {
  31078. return Material._LineStripDrawMode;
  31079. },
  31080. enumerable: true,
  31081. configurable: true
  31082. });
  31083. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31084. /**
  31085. * Returns the triangle strip draw mode.
  31086. */
  31087. get: function () {
  31088. return Material._TriangleStripDrawMode;
  31089. },
  31090. enumerable: true,
  31091. configurable: true
  31092. });
  31093. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31094. /**
  31095. * Returns the triangle fan draw mode.
  31096. */
  31097. get: function () {
  31098. return Material._TriangleFanDrawMode;
  31099. },
  31100. enumerable: true,
  31101. configurable: true
  31102. });
  31103. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31104. /**
  31105. * Returns the clock-wise side orientation.
  31106. */
  31107. get: function () {
  31108. return Material._ClockWiseSideOrientation;
  31109. },
  31110. enumerable: true,
  31111. configurable: true
  31112. });
  31113. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31114. /**
  31115. * Returns the counter clock-wise side orientation.
  31116. */
  31117. get: function () {
  31118. return Material._CounterClockWiseSideOrientation;
  31119. },
  31120. enumerable: true,
  31121. configurable: true
  31122. });
  31123. Object.defineProperty(Material, "TextureDirtyFlag", {
  31124. /**
  31125. * Returns the dirty texture flag value.
  31126. */
  31127. get: function () {
  31128. return Material._TextureDirtyFlag;
  31129. },
  31130. enumerable: true,
  31131. configurable: true
  31132. });
  31133. Object.defineProperty(Material, "LightDirtyFlag", {
  31134. /**
  31135. * Returns the dirty light flag value.
  31136. */
  31137. get: function () {
  31138. return Material._LightDirtyFlag;
  31139. },
  31140. enumerable: true,
  31141. configurable: true
  31142. });
  31143. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31144. /**
  31145. * Returns the dirty fresnel flag value.
  31146. */
  31147. get: function () {
  31148. return Material._FresnelDirtyFlag;
  31149. },
  31150. enumerable: true,
  31151. configurable: true
  31152. });
  31153. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31154. /**
  31155. * Returns the dirty attributes flag value.
  31156. */
  31157. get: function () {
  31158. return Material._AttributesDirtyFlag;
  31159. },
  31160. enumerable: true,
  31161. configurable: true
  31162. });
  31163. Object.defineProperty(Material, "MiscDirtyFlag", {
  31164. /**
  31165. * Returns the dirty misc flag value.
  31166. */
  31167. get: function () {
  31168. return Material._MiscDirtyFlag;
  31169. },
  31170. enumerable: true,
  31171. configurable: true
  31172. });
  31173. Object.defineProperty(Material.prototype, "alpha", {
  31174. /**
  31175. * Gets the alpha value of the material.
  31176. */
  31177. get: function () {
  31178. return this._alpha;
  31179. },
  31180. /**
  31181. * Sets the alpha value of the material.
  31182. */
  31183. set: function (value) {
  31184. if (this._alpha === value) {
  31185. return;
  31186. }
  31187. this._alpha = value;
  31188. this.markAsDirty(Material.MiscDirtyFlag);
  31189. },
  31190. enumerable: true,
  31191. configurable: true
  31192. });
  31193. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31194. /**
  31195. * Gets the back-face culling state.
  31196. */
  31197. get: function () {
  31198. return this._backFaceCulling;
  31199. },
  31200. /**
  31201. * Sets the back-face culling state.
  31202. */
  31203. set: function (value) {
  31204. if (this._backFaceCulling === value) {
  31205. return;
  31206. }
  31207. this._backFaceCulling = value;
  31208. this.markAsDirty(Material.TextureDirtyFlag);
  31209. },
  31210. enumerable: true,
  31211. configurable: true
  31212. });
  31213. Object.defineProperty(Material.prototype, "onDispose", {
  31214. /**
  31215. * Called during a dispose event.
  31216. */
  31217. set: function (callback) {
  31218. if (this._onDisposeObserver) {
  31219. this.onDisposeObservable.remove(this._onDisposeObserver);
  31220. }
  31221. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31222. },
  31223. enumerable: true,
  31224. configurable: true
  31225. });
  31226. Object.defineProperty(Material.prototype, "onBind", {
  31227. /**
  31228. * Called during a bind event.
  31229. */
  31230. set: function (callback) {
  31231. if (this._onBindObserver) {
  31232. this.onBindObservable.remove(this._onBindObserver);
  31233. }
  31234. this._onBindObserver = this.onBindObservable.add(callback);
  31235. },
  31236. enumerable: true,
  31237. configurable: true
  31238. });
  31239. Object.defineProperty(Material.prototype, "alphaMode", {
  31240. /**
  31241. * Gets the value of the alpha mode.
  31242. */
  31243. get: function () {
  31244. return this._alphaMode;
  31245. },
  31246. /**
  31247. * Sets the value of the alpha mode.
  31248. */
  31249. set: function (value) {
  31250. if (this._alphaMode === value) {
  31251. return;
  31252. }
  31253. this._alphaMode = value;
  31254. this.markAsDirty(Material.TextureDirtyFlag);
  31255. },
  31256. enumerable: true,
  31257. configurable: true
  31258. });
  31259. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31260. /**
  31261. * Gets the depth pre-pass value.
  31262. */
  31263. get: function () {
  31264. return this._needDepthPrePass;
  31265. },
  31266. /**
  31267. * Sets the need depth pre-pass value.
  31268. */
  31269. set: function (value) {
  31270. if (this._needDepthPrePass === value) {
  31271. return;
  31272. }
  31273. this._needDepthPrePass = value;
  31274. if (this._needDepthPrePass) {
  31275. this.checkReadyOnEveryCall = true;
  31276. }
  31277. },
  31278. enumerable: true,
  31279. configurable: true
  31280. });
  31281. Object.defineProperty(Material.prototype, "fogEnabled", {
  31282. /**
  31283. * Gets the value of the fog enabled state.
  31284. */
  31285. get: function () {
  31286. return this._fogEnabled;
  31287. },
  31288. /**
  31289. * Sets the state for enabling fog.
  31290. */
  31291. set: function (value) {
  31292. if (this._fogEnabled === value) {
  31293. return;
  31294. }
  31295. this._fogEnabled = value;
  31296. this.markAsDirty(Material.MiscDirtyFlag);
  31297. },
  31298. enumerable: true,
  31299. configurable: true
  31300. });
  31301. Object.defineProperty(Material.prototype, "wireframe", {
  31302. /**
  31303. * Gets a value specifying if wireframe mode is enabled.
  31304. */
  31305. get: function () {
  31306. return this._fillMode === Material.WireFrameFillMode;
  31307. },
  31308. /**
  31309. * Sets the state of wireframe mode.
  31310. */
  31311. set: function (value) {
  31312. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31313. },
  31314. enumerable: true,
  31315. configurable: true
  31316. });
  31317. Object.defineProperty(Material.prototype, "pointsCloud", {
  31318. /**
  31319. * Gets the value specifying if point clouds are enabled.
  31320. */
  31321. get: function () {
  31322. return this._fillMode === Material.PointFillMode;
  31323. },
  31324. /**
  31325. * Sets the state of point cloud mode.
  31326. */
  31327. set: function (value) {
  31328. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31329. },
  31330. enumerable: true,
  31331. configurable: true
  31332. });
  31333. Object.defineProperty(Material.prototype, "fillMode", {
  31334. /**
  31335. * Gets the material fill mode.
  31336. */
  31337. get: function () {
  31338. return this._fillMode;
  31339. },
  31340. /**
  31341. * Sets the material fill mode.
  31342. */
  31343. set: function (value) {
  31344. if (this._fillMode === value) {
  31345. return;
  31346. }
  31347. this._fillMode = value;
  31348. this.markAsDirty(Material.MiscDirtyFlag);
  31349. },
  31350. enumerable: true,
  31351. configurable: true
  31352. });
  31353. /**
  31354. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31355. * subclasses should override adding information pertainent to themselves.
  31356. * @returns - String with material information.
  31357. */
  31358. Material.prototype.toString = function (fullDetails) {
  31359. var ret = "Name: " + this.name;
  31360. if (fullDetails) {
  31361. }
  31362. return ret;
  31363. };
  31364. /**
  31365. * Gets the class name of the material.
  31366. * @returns - String with the class name of the material.
  31367. */
  31368. Material.prototype.getClassName = function () {
  31369. return "Material";
  31370. };
  31371. Object.defineProperty(Material.prototype, "isFrozen", {
  31372. /**
  31373. * Specifies if updates for the material been locked.
  31374. */
  31375. get: function () {
  31376. return this.checkReadyOnlyOnce;
  31377. },
  31378. enumerable: true,
  31379. configurable: true
  31380. });
  31381. /**
  31382. * Locks updates for the material.
  31383. */
  31384. Material.prototype.freeze = function () {
  31385. this.checkReadyOnlyOnce = true;
  31386. };
  31387. /**
  31388. * Unlocks updates for the material.
  31389. */
  31390. Material.prototype.unfreeze = function () {
  31391. this.checkReadyOnlyOnce = false;
  31392. };
  31393. /**
  31394. * Specifies if the material is ready to be used.
  31395. * @param mesh - BJS mesh.
  31396. * @param useInstances - Specifies if instances should be used.
  31397. * @returns - Boolean indicating if the material is ready to be used.
  31398. */
  31399. Material.prototype.isReady = function (mesh, useInstances) {
  31400. return true;
  31401. };
  31402. /**
  31403. * Specifies that the submesh is ready to be used.
  31404. * @param mesh - BJS mesh.
  31405. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31406. * @param useInstances - Specifies that instances should be used.
  31407. * @returns - boolean indicating that the submesh is ready or not.
  31408. */
  31409. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31410. return false;
  31411. };
  31412. /**
  31413. * Returns the material effect.
  31414. * @returns - Nullable material effect.
  31415. */
  31416. Material.prototype.getEffect = function () {
  31417. return this._effect;
  31418. };
  31419. /**
  31420. * Returns the BJS scene.
  31421. * @returns - BJS Scene.
  31422. */
  31423. Material.prototype.getScene = function () {
  31424. return this._scene;
  31425. };
  31426. /**
  31427. * Specifies if the material will require alpha blending
  31428. * @returns - Boolean specifying if alpha blending is needed.
  31429. */
  31430. Material.prototype.needAlphaBlending = function () {
  31431. return (this.alpha < 1.0);
  31432. };
  31433. /**
  31434. * Specifies if the mesh will require alpha blending.
  31435. * @param mesh - BJS mesh.
  31436. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31437. */
  31438. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31439. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31440. };
  31441. /**
  31442. * Specifies if this material should be rendered in alpha test mode.
  31443. * @returns - Boolean specifying if an alpha test is needed.
  31444. */
  31445. Material.prototype.needAlphaTesting = function () {
  31446. return false;
  31447. };
  31448. /**
  31449. * Gets the texture used for the alpha test.
  31450. * @returns - Nullable alpha test texture.
  31451. */
  31452. Material.prototype.getAlphaTestTexture = function () {
  31453. return null;
  31454. };
  31455. /**
  31456. * Marks the material to indicate that it needs to be re-calculated.
  31457. */
  31458. Material.prototype.markDirty = function () {
  31459. this._wasPreviouslyReady = false;
  31460. };
  31461. Material.prototype._preBind = function (effect, overrideOrientation) {
  31462. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31463. var engine = this._scene.getEngine();
  31464. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31465. var reverse = orientation === Material.ClockWiseSideOrientation;
  31466. engine.enableEffect(effect ? effect : this._effect);
  31467. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31468. return reverse;
  31469. };
  31470. /**
  31471. * Binds the material to the mesh.
  31472. * @param world - World transformation matrix.
  31473. * @param mesh - Mesh to bind the material to.
  31474. */
  31475. Material.prototype.bind = function (world, mesh) {
  31476. };
  31477. /**
  31478. * Binds the submesh to the material.
  31479. * @param world - World transformation matrix.
  31480. * @param mesh - Mesh containing the submesh.
  31481. * @param subMesh - Submesh to bind the material to.
  31482. */
  31483. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31484. };
  31485. /**
  31486. * Binds the world matrix to the material.
  31487. * @param world - World transformation matrix.
  31488. */
  31489. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31490. };
  31491. /**
  31492. * Binds the scene's uniform buffer to the effect.
  31493. * @param effect - Effect to bind to the scene uniform buffer.
  31494. * @param sceneUbo - Scene uniform buffer.
  31495. */
  31496. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31497. sceneUbo.bindToEffect(effect, "Scene");
  31498. };
  31499. /**
  31500. * Binds the view matrix to the effect.
  31501. * @param effect - Effect to bind the view matrix to.
  31502. */
  31503. Material.prototype.bindView = function (effect) {
  31504. if (!this._useUBO) {
  31505. effect.setMatrix("view", this.getScene().getViewMatrix());
  31506. }
  31507. else {
  31508. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31509. }
  31510. };
  31511. /**
  31512. * Binds the view projection matrix to the effect.
  31513. * @param effect - Effect to bind the view projection matrix to.
  31514. */
  31515. Material.prototype.bindViewProjection = function (effect) {
  31516. if (!this._useUBO) {
  31517. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31518. }
  31519. else {
  31520. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31521. }
  31522. };
  31523. /**
  31524. * Specifies if material alpha testing should be turned on for the mesh.
  31525. * @param mesh - BJS mesh.
  31526. */
  31527. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31528. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31529. };
  31530. /**
  31531. * Processes to execute after binding the material to a mesh.
  31532. * @param mesh - BJS mesh.
  31533. */
  31534. Material.prototype._afterBind = function (mesh) {
  31535. this._scene._cachedMaterial = this;
  31536. if (mesh) {
  31537. this._scene._cachedVisibility = mesh.visibility;
  31538. }
  31539. else {
  31540. this._scene._cachedVisibility = 1;
  31541. }
  31542. if (mesh) {
  31543. this.onBindObservable.notifyObservers(mesh);
  31544. }
  31545. if (this.disableDepthWrite) {
  31546. var engine = this._scene.getEngine();
  31547. this._cachedDepthWriteState = engine.getDepthWrite();
  31548. engine.setDepthWrite(false);
  31549. }
  31550. };
  31551. /**
  31552. * Unbinds the material from the mesh.
  31553. */
  31554. Material.prototype.unbind = function () {
  31555. this.onUnBindObservable.notifyObservers(this);
  31556. if (this.disableDepthWrite) {
  31557. var engine = this._scene.getEngine();
  31558. engine.setDepthWrite(this._cachedDepthWriteState);
  31559. }
  31560. };
  31561. /**
  31562. * Gets the active textures from the material.
  31563. * @returns - Array of textures.
  31564. */
  31565. Material.prototype.getActiveTextures = function () {
  31566. return [];
  31567. };
  31568. /**
  31569. * Specifies if the material uses a texture.
  31570. * @param texture - Texture to check against the material.
  31571. * @returns - Boolean specifying if the material uses the texture.
  31572. */
  31573. Material.prototype.hasTexture = function (texture) {
  31574. return false;
  31575. };
  31576. /**
  31577. * Makes a duplicate of the material, and gives it a new name.
  31578. * @param name - Name to call the duplicated material.
  31579. * @returns - Nullable cloned material
  31580. */
  31581. Material.prototype.clone = function (name) {
  31582. return null;
  31583. };
  31584. /**
  31585. * Gets the meshes bound to the material.
  31586. * @returns - Array of meshes bound to the material.
  31587. */
  31588. Material.prototype.getBindedMeshes = function () {
  31589. var result = new Array();
  31590. for (var index = 0; index < this._scene.meshes.length; index++) {
  31591. var mesh = this._scene.meshes[index];
  31592. if (mesh.material === this) {
  31593. result.push(mesh);
  31594. }
  31595. }
  31596. return result;
  31597. };
  31598. /**
  31599. * Force shader compilation
  31600. * @param mesh - BJS mesh.
  31601. * @param onCompiled - function to execute once the material is compiled.
  31602. * @param options - options to pass to this function.
  31603. */
  31604. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31605. var _this = this;
  31606. var localOptions = __assign({ clipPlane: false }, options);
  31607. var subMesh = new BABYLON.BaseSubMesh();
  31608. var scene = this.getScene();
  31609. var checkReady = function () {
  31610. if (!_this._scene || !_this._scene.getEngine()) {
  31611. return;
  31612. }
  31613. if (subMesh._materialDefines) {
  31614. subMesh._materialDefines._renderId = -1;
  31615. }
  31616. var clipPlaneState = scene.clipPlane;
  31617. if (localOptions.clipPlane) {
  31618. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31619. }
  31620. if (_this.storeEffectOnSubMeshes) {
  31621. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31622. if (onCompiled) {
  31623. onCompiled(_this);
  31624. }
  31625. }
  31626. else {
  31627. setTimeout(checkReady, 16);
  31628. }
  31629. }
  31630. else {
  31631. if (_this.isReady(mesh)) {
  31632. if (onCompiled) {
  31633. onCompiled(_this);
  31634. }
  31635. }
  31636. else {
  31637. setTimeout(checkReady, 16);
  31638. }
  31639. }
  31640. if (localOptions.clipPlane) {
  31641. scene.clipPlane = clipPlaneState;
  31642. }
  31643. };
  31644. checkReady();
  31645. };
  31646. /**
  31647. * Force shader compilation.
  31648. * @param mesh The mesh that will use this material
  31649. * @param options Additional options for compiling the shaders
  31650. * @returns A promise that resolves when the compilation completes
  31651. */
  31652. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31653. var _this = this;
  31654. return new Promise(function (resolve) {
  31655. _this.forceCompilation(mesh, function () {
  31656. resolve();
  31657. }, options);
  31658. });
  31659. };
  31660. /**
  31661. * Marks a define in the material to indicate that it needs to be re-computed.
  31662. * @param flag - Material define flag.
  31663. */
  31664. Material.prototype.markAsDirty = function (flag) {
  31665. if (flag & Material.TextureDirtyFlag) {
  31666. this._markAllSubMeshesAsTexturesDirty();
  31667. }
  31668. if (flag & Material.LightDirtyFlag) {
  31669. this._markAllSubMeshesAsLightsDirty();
  31670. }
  31671. if (flag & Material.FresnelDirtyFlag) {
  31672. this._markAllSubMeshesAsFresnelDirty();
  31673. }
  31674. if (flag & Material.AttributesDirtyFlag) {
  31675. this._markAllSubMeshesAsAttributesDirty();
  31676. }
  31677. if (flag & Material.MiscDirtyFlag) {
  31678. this._markAllSubMeshesAsMiscDirty();
  31679. }
  31680. this.getScene().resetCachedMaterial();
  31681. };
  31682. /**
  31683. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31684. * @param func - function which checks material defines against the submeshes.
  31685. */
  31686. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31687. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31688. var mesh = _a[_i];
  31689. if (!mesh.subMeshes) {
  31690. continue;
  31691. }
  31692. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31693. var subMesh = _c[_b];
  31694. if (subMesh.getMaterial() !== this) {
  31695. continue;
  31696. }
  31697. if (!subMesh._materialDefines) {
  31698. continue;
  31699. }
  31700. func(subMesh._materialDefines);
  31701. }
  31702. }
  31703. };
  31704. /**
  31705. * Indicates that image processing needs to be re-calculated for all submeshes.
  31706. */
  31707. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31708. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31709. };
  31710. /**
  31711. * Indicates that textures need to be re-calculated for all submeshes.
  31712. */
  31713. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31714. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31715. };
  31716. /**
  31717. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31718. */
  31719. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31720. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31721. };
  31722. /**
  31723. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31724. */
  31725. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31726. this._markAllSubMeshesAsDirty(function (defines) {
  31727. defines.markAsFresnelDirty();
  31728. defines.markAsMiscDirty();
  31729. });
  31730. };
  31731. /**
  31732. * Indicates that lights need to be re-calculated for all submeshes.
  31733. */
  31734. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31735. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31736. };
  31737. /**
  31738. * Indicates that attributes need to be re-calculated for all submeshes.
  31739. */
  31740. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31741. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31742. };
  31743. /**
  31744. * Indicates that misc needs to be re-calculated for all submeshes.
  31745. */
  31746. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31747. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31748. };
  31749. /**
  31750. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31751. */
  31752. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31753. this._markAllSubMeshesAsDirty(function (defines) {
  31754. defines.markAsTexturesDirty();
  31755. defines.markAsMiscDirty();
  31756. });
  31757. };
  31758. /**
  31759. * Disposes the material.
  31760. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31761. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31762. */
  31763. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31764. // Animations
  31765. this.getScene().stopAnimation(this);
  31766. this.getScene().freeProcessedMaterials();
  31767. // Remove from scene
  31768. var index = this._scene.materials.indexOf(this);
  31769. if (index >= 0) {
  31770. this._scene.materials.splice(index, 1);
  31771. }
  31772. // Remove from meshes
  31773. for (index = 0; index < this._scene.meshes.length; index++) {
  31774. var mesh = this._scene.meshes[index];
  31775. if (mesh.material === this) {
  31776. mesh.material = null;
  31777. if (mesh.geometry) {
  31778. var geometry = (mesh.geometry);
  31779. if (this.storeEffectOnSubMeshes) {
  31780. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31781. var subMesh = _a[_i];
  31782. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31783. if (forceDisposeEffect && subMesh._materialEffect) {
  31784. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31785. }
  31786. }
  31787. }
  31788. else {
  31789. geometry._releaseVertexArrayObject(this._effect);
  31790. }
  31791. }
  31792. }
  31793. }
  31794. this._uniformBuffer.dispose();
  31795. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31796. if (forceDisposeEffect && this._effect) {
  31797. if (!this.storeEffectOnSubMeshes) {
  31798. this._scene.getEngine()._releaseEffect(this._effect);
  31799. }
  31800. this._effect = null;
  31801. }
  31802. // Callback
  31803. this.onDisposeObservable.notifyObservers(this);
  31804. this.onDisposeObservable.clear();
  31805. this.onBindObservable.clear();
  31806. this.onUnBindObservable.clear();
  31807. };
  31808. /**
  31809. * Serializes this material.
  31810. * @returns - serialized material object.
  31811. */
  31812. Material.prototype.serialize = function () {
  31813. return BABYLON.SerializationHelper.Serialize(this);
  31814. };
  31815. /**
  31816. * Creates a MultiMaterial from parse MultiMaterial data.
  31817. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31818. * @param scene - BJS scene.
  31819. * @returns - MultiMaterial.
  31820. */
  31821. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31822. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31823. multiMaterial.id = parsedMultiMaterial.id;
  31824. if (BABYLON.Tags) {
  31825. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31826. }
  31827. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31828. var subMatId = parsedMultiMaterial.materials[matIndex];
  31829. if (subMatId) {
  31830. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31831. }
  31832. else {
  31833. multiMaterial.subMaterials.push(null);
  31834. }
  31835. }
  31836. return multiMaterial;
  31837. };
  31838. /**
  31839. * Creates a material from parsed material data.
  31840. * @param parsedMaterial - Parsed material data.
  31841. * @param scene - BJS scene.
  31842. * @param rootUrl - Root URL containing the material information.
  31843. * @returns - Parsed material.
  31844. */
  31845. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31846. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  31847. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31848. }
  31849. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31850. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31851. if (!BABYLON.LegacyPBRMaterial) {
  31852. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31853. return;
  31854. }
  31855. }
  31856. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31857. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31858. ;
  31859. };
  31860. // Triangle views
  31861. Material._TriangleFillMode = 0;
  31862. Material._WireFrameFillMode = 1;
  31863. Material._PointFillMode = 2;
  31864. // Draw modes
  31865. Material._PointListDrawMode = 3;
  31866. Material._LineListDrawMode = 4;
  31867. Material._LineLoopDrawMode = 5;
  31868. Material._LineStripDrawMode = 6;
  31869. Material._TriangleStripDrawMode = 7;
  31870. Material._TriangleFanDrawMode = 8;
  31871. /**
  31872. * Stores the clock-wise side orientation.
  31873. */
  31874. Material._ClockWiseSideOrientation = 0;
  31875. /**
  31876. * Stores the counter clock-wise side orientation.
  31877. */
  31878. Material._CounterClockWiseSideOrientation = 1;
  31879. /**
  31880. * The dirty texture flag value.
  31881. */
  31882. Material._TextureDirtyFlag = 1;
  31883. /**
  31884. * The dirty light flag value.
  31885. */
  31886. Material._LightDirtyFlag = 2;
  31887. /**
  31888. * The dirty fresnel flag value.
  31889. */
  31890. Material._FresnelDirtyFlag = 4;
  31891. /**
  31892. * The dirty attribute flag value.
  31893. */
  31894. Material._AttributesDirtyFlag = 8;
  31895. /**
  31896. * The dirty misc flag value.
  31897. */
  31898. Material._MiscDirtyFlag = 16;
  31899. __decorate([
  31900. BABYLON.serialize()
  31901. ], Material.prototype, "id", void 0);
  31902. __decorate([
  31903. BABYLON.serialize()
  31904. ], Material.prototype, "name", void 0);
  31905. __decorate([
  31906. BABYLON.serialize()
  31907. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31908. __decorate([
  31909. BABYLON.serialize()
  31910. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31911. __decorate([
  31912. BABYLON.serialize()
  31913. ], Material.prototype, "state", void 0);
  31914. __decorate([
  31915. BABYLON.serialize("alpha")
  31916. ], Material.prototype, "_alpha", void 0);
  31917. __decorate([
  31918. BABYLON.serialize("backFaceCulling")
  31919. ], Material.prototype, "_backFaceCulling", void 0);
  31920. __decorate([
  31921. BABYLON.serialize()
  31922. ], Material.prototype, "sideOrientation", void 0);
  31923. __decorate([
  31924. BABYLON.serialize("alphaMode")
  31925. ], Material.prototype, "_alphaMode", void 0);
  31926. __decorate([
  31927. BABYLON.serialize()
  31928. ], Material.prototype, "_needDepthPrePass", void 0);
  31929. __decorate([
  31930. BABYLON.serialize()
  31931. ], Material.prototype, "disableDepthWrite", void 0);
  31932. __decorate([
  31933. BABYLON.serialize()
  31934. ], Material.prototype, "forceDepthWrite", void 0);
  31935. __decorate([
  31936. BABYLON.serialize()
  31937. ], Material.prototype, "separateCullingPass", void 0);
  31938. __decorate([
  31939. BABYLON.serialize("fogEnabled")
  31940. ], Material.prototype, "_fogEnabled", void 0);
  31941. __decorate([
  31942. BABYLON.serialize()
  31943. ], Material.prototype, "pointSize", void 0);
  31944. __decorate([
  31945. BABYLON.serialize()
  31946. ], Material.prototype, "zOffset", void 0);
  31947. __decorate([
  31948. BABYLON.serialize()
  31949. ], Material.prototype, "wireframe", null);
  31950. __decorate([
  31951. BABYLON.serialize()
  31952. ], Material.prototype, "pointsCloud", null);
  31953. __decorate([
  31954. BABYLON.serialize()
  31955. ], Material.prototype, "fillMode", null);
  31956. return Material;
  31957. }());
  31958. BABYLON.Material = Material;
  31959. })(BABYLON || (BABYLON = {}));
  31960. //# sourceMappingURL=babylon.material.js.map
  31961. var BABYLON;
  31962. (function (BABYLON) {
  31963. var UniformBuffer = /** @class */ (function () {
  31964. /**
  31965. * Uniform buffer objects.
  31966. *
  31967. * Handles blocks of uniform on the GPU.
  31968. *
  31969. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31970. *
  31971. * For more information, please refer to :
  31972. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31973. */
  31974. function UniformBuffer(engine, data, dynamic) {
  31975. this._engine = engine;
  31976. this._noUBO = !engine.supportsUniformBuffers;
  31977. this._dynamic = dynamic;
  31978. this._data = data || [];
  31979. this._uniformLocations = {};
  31980. this._uniformSizes = {};
  31981. this._uniformLocationPointer = 0;
  31982. this._needSync = false;
  31983. if (this._noUBO) {
  31984. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31985. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31986. this.updateFloat = this._updateFloatForEffect;
  31987. this.updateFloat2 = this._updateFloat2ForEffect;
  31988. this.updateFloat3 = this._updateFloat3ForEffect;
  31989. this.updateFloat4 = this._updateFloat4ForEffect;
  31990. this.updateMatrix = this._updateMatrixForEffect;
  31991. this.updateVector3 = this._updateVector3ForEffect;
  31992. this.updateVector4 = this._updateVector4ForEffect;
  31993. this.updateColor3 = this._updateColor3ForEffect;
  31994. this.updateColor4 = this._updateColor4ForEffect;
  31995. }
  31996. else {
  31997. this._engine._uniformBuffers.push(this);
  31998. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31999. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32000. this.updateFloat = this._updateFloatForUniform;
  32001. this.updateFloat2 = this._updateFloat2ForUniform;
  32002. this.updateFloat3 = this._updateFloat3ForUniform;
  32003. this.updateFloat4 = this._updateFloat4ForUniform;
  32004. this.updateMatrix = this._updateMatrixForUniform;
  32005. this.updateVector3 = this._updateVector3ForUniform;
  32006. this.updateVector4 = this._updateVector4ForUniform;
  32007. this.updateColor3 = this._updateColor3ForUniform;
  32008. this.updateColor4 = this._updateColor4ForUniform;
  32009. }
  32010. }
  32011. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32012. // Properties
  32013. /**
  32014. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32015. * or just falling back on setUniformXXX calls.
  32016. */
  32017. get: function () {
  32018. return !this._noUBO;
  32019. },
  32020. enumerable: true,
  32021. configurable: true
  32022. });
  32023. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32024. /**
  32025. * Indicates if the WebGL underlying uniform buffer is in sync
  32026. * with the javascript cache data.
  32027. */
  32028. get: function () {
  32029. return !this._needSync;
  32030. },
  32031. enumerable: true,
  32032. configurable: true
  32033. });
  32034. /**
  32035. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32036. * Also, a dynamic UniformBuffer will disable cache verification and always
  32037. * update the underlying WebGL uniform buffer to the GPU.
  32038. */
  32039. UniformBuffer.prototype.isDynamic = function () {
  32040. return this._dynamic !== undefined;
  32041. };
  32042. /**
  32043. * The data cache on JS side.
  32044. */
  32045. UniformBuffer.prototype.getData = function () {
  32046. return this._bufferData;
  32047. };
  32048. /**
  32049. * The underlying WebGL Uniform buffer.
  32050. */
  32051. UniformBuffer.prototype.getBuffer = function () {
  32052. return this._buffer;
  32053. };
  32054. /**
  32055. * std140 layout specifies how to align data within an UBO structure.
  32056. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32057. * for specs.
  32058. */
  32059. UniformBuffer.prototype._fillAlignment = function (size) {
  32060. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32061. // and 4x4 matrices
  32062. // TODO : change if other types are used
  32063. var alignment;
  32064. if (size <= 2) {
  32065. alignment = size;
  32066. }
  32067. else {
  32068. alignment = 4;
  32069. }
  32070. if ((this._uniformLocationPointer % alignment) !== 0) {
  32071. var oldPointer = this._uniformLocationPointer;
  32072. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32073. var diff = this._uniformLocationPointer - oldPointer;
  32074. for (var i = 0; i < diff; i++) {
  32075. this._data.push(0);
  32076. }
  32077. }
  32078. };
  32079. /**
  32080. * Adds an uniform in the buffer.
  32081. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32082. * for the layout to be correct !
  32083. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32084. * @param {number|number[]} size Data size, or data directly.
  32085. */
  32086. UniformBuffer.prototype.addUniform = function (name, size) {
  32087. if (this._noUBO) {
  32088. return;
  32089. }
  32090. if (this._uniformLocations[name] !== undefined) {
  32091. // Already existing uniform
  32092. return;
  32093. }
  32094. // This function must be called in the order of the shader layout !
  32095. // size can be the size of the uniform, or data directly
  32096. var data;
  32097. if (size instanceof Array) {
  32098. data = size;
  32099. size = data.length;
  32100. }
  32101. else {
  32102. size = size;
  32103. data = [];
  32104. // Fill with zeros
  32105. for (var i = 0; i < size; i++) {
  32106. data.push(0);
  32107. }
  32108. }
  32109. this._fillAlignment(size);
  32110. this._uniformSizes[name] = size;
  32111. this._uniformLocations[name] = this._uniformLocationPointer;
  32112. this._uniformLocationPointer += size;
  32113. for (var i = 0; i < size; i++) {
  32114. this._data.push(data[i]);
  32115. }
  32116. this._needSync = true;
  32117. };
  32118. /**
  32119. * Wrapper for addUniform.
  32120. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32121. * @param {Matrix} mat A 4x4 matrix.
  32122. */
  32123. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32124. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32125. };
  32126. /**
  32127. * Wrapper for addUniform.
  32128. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32129. * @param {number} x
  32130. * @param {number} y
  32131. */
  32132. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32133. var temp = [x, y];
  32134. this.addUniform(name, temp);
  32135. };
  32136. /**
  32137. * Wrapper for addUniform.
  32138. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32139. * @param {number} x
  32140. * @param {number} y
  32141. * @param {number} z
  32142. */
  32143. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32144. var temp = [x, y, z];
  32145. this.addUniform(name, temp);
  32146. };
  32147. /**
  32148. * Wrapper for addUniform.
  32149. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32150. * @param {Color3} color
  32151. */
  32152. UniformBuffer.prototype.addColor3 = function (name, color) {
  32153. var temp = new Array();
  32154. color.toArray(temp);
  32155. this.addUniform(name, temp);
  32156. };
  32157. /**
  32158. * Wrapper for addUniform.
  32159. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32160. * @param {Color3} color
  32161. * @param {number} alpha
  32162. */
  32163. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32164. var temp = new Array();
  32165. color.toArray(temp);
  32166. temp.push(alpha);
  32167. this.addUniform(name, temp);
  32168. };
  32169. /**
  32170. * Wrapper for addUniform.
  32171. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32172. * @param {Vector3} vector
  32173. */
  32174. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32175. var temp = new Array();
  32176. vector.toArray(temp);
  32177. this.addUniform(name, temp);
  32178. };
  32179. /**
  32180. * Wrapper for addUniform.
  32181. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32182. */
  32183. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32184. this.addUniform(name, 12);
  32185. };
  32186. /**
  32187. * Wrapper for addUniform.
  32188. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32189. */
  32190. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32191. this.addUniform(name, 8);
  32192. };
  32193. /**
  32194. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32195. */
  32196. UniformBuffer.prototype.create = function () {
  32197. if (this._noUBO) {
  32198. return;
  32199. }
  32200. if (this._buffer) {
  32201. return; // nothing to do
  32202. }
  32203. // See spec, alignment must be filled as a vec4
  32204. this._fillAlignment(4);
  32205. this._bufferData = new Float32Array(this._data);
  32206. this._rebuild();
  32207. this._needSync = true;
  32208. };
  32209. UniformBuffer.prototype._rebuild = function () {
  32210. if (this._noUBO) {
  32211. return;
  32212. }
  32213. if (this._dynamic) {
  32214. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32215. }
  32216. else {
  32217. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32218. }
  32219. };
  32220. /**
  32221. * Updates the WebGL Uniform Buffer on the GPU.
  32222. * If the `dynamic` flag is set to true, no cache comparison is done.
  32223. * Otherwise, the buffer will be updated only if the cache differs.
  32224. */
  32225. UniformBuffer.prototype.update = function () {
  32226. if (!this._buffer) {
  32227. this.create();
  32228. return;
  32229. }
  32230. if (!this._dynamic && !this._needSync) {
  32231. return;
  32232. }
  32233. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32234. this._needSync = false;
  32235. };
  32236. /**
  32237. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32238. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32239. * @param {number[]|Float32Array} data Flattened data
  32240. * @param {number} size Size of the data.
  32241. */
  32242. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32243. var location = this._uniformLocations[uniformName];
  32244. if (location === undefined) {
  32245. if (this._buffer) {
  32246. // Cannot add an uniform if the buffer is already created
  32247. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32248. return;
  32249. }
  32250. this.addUniform(uniformName, size);
  32251. location = this._uniformLocations[uniformName];
  32252. }
  32253. if (!this._buffer) {
  32254. this.create();
  32255. }
  32256. if (!this._dynamic) {
  32257. // Cache for static uniform buffers
  32258. var changed = false;
  32259. for (var i = 0; i < size; i++) {
  32260. if (this._bufferData[location + i] !== data[i]) {
  32261. changed = true;
  32262. this._bufferData[location + i] = data[i];
  32263. }
  32264. }
  32265. this._needSync = this._needSync || changed;
  32266. }
  32267. else {
  32268. // No cache for dynamic
  32269. for (var i = 0; i < size; i++) {
  32270. this._bufferData[location + i] = data[i];
  32271. }
  32272. }
  32273. };
  32274. // Update methods
  32275. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32276. // To match std140, matrix must be realigned
  32277. for (var i = 0; i < 3; i++) {
  32278. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32279. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32280. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32281. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32282. }
  32283. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32284. };
  32285. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32286. this._currentEffect.setMatrix3x3(name, matrix);
  32287. };
  32288. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32289. this._currentEffect.setMatrix2x2(name, matrix);
  32290. };
  32291. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32292. // To match std140, matrix must be realigned
  32293. for (var i = 0; i < 2; i++) {
  32294. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32295. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32296. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32297. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32298. }
  32299. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32300. };
  32301. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32302. this._currentEffect.setFloat(name, x);
  32303. };
  32304. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32305. UniformBuffer._tempBuffer[0] = x;
  32306. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32307. };
  32308. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32309. if (suffix === void 0) { suffix = ""; }
  32310. this._currentEffect.setFloat2(name + suffix, x, y);
  32311. };
  32312. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32313. if (suffix === void 0) { suffix = ""; }
  32314. UniformBuffer._tempBuffer[0] = x;
  32315. UniformBuffer._tempBuffer[1] = y;
  32316. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32317. };
  32318. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32319. if (suffix === void 0) { suffix = ""; }
  32320. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32321. };
  32322. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32323. if (suffix === void 0) { suffix = ""; }
  32324. UniformBuffer._tempBuffer[0] = x;
  32325. UniformBuffer._tempBuffer[1] = y;
  32326. UniformBuffer._tempBuffer[2] = z;
  32327. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32328. };
  32329. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32330. if (suffix === void 0) { suffix = ""; }
  32331. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32332. };
  32333. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32334. if (suffix === void 0) { suffix = ""; }
  32335. UniformBuffer._tempBuffer[0] = x;
  32336. UniformBuffer._tempBuffer[1] = y;
  32337. UniformBuffer._tempBuffer[2] = z;
  32338. UniformBuffer._tempBuffer[3] = w;
  32339. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32340. };
  32341. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32342. this._currentEffect.setMatrix(name, mat);
  32343. };
  32344. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32345. this.updateUniform(name, mat.toArray(), 16);
  32346. };
  32347. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32348. this._currentEffect.setVector3(name, vector);
  32349. };
  32350. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32351. vector.toArray(UniformBuffer._tempBuffer);
  32352. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32353. };
  32354. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32355. this._currentEffect.setVector4(name, vector);
  32356. };
  32357. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32358. vector.toArray(UniformBuffer._tempBuffer);
  32359. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32360. };
  32361. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32362. if (suffix === void 0) { suffix = ""; }
  32363. this._currentEffect.setColor3(name + suffix, color);
  32364. };
  32365. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32366. if (suffix === void 0) { suffix = ""; }
  32367. color.toArray(UniformBuffer._tempBuffer);
  32368. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32369. };
  32370. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32371. if (suffix === void 0) { suffix = ""; }
  32372. this._currentEffect.setColor4(name + suffix, color, alpha);
  32373. };
  32374. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32375. if (suffix === void 0) { suffix = ""; }
  32376. color.toArray(UniformBuffer._tempBuffer);
  32377. UniformBuffer._tempBuffer[3] = alpha;
  32378. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32379. };
  32380. /**
  32381. * Sets a sampler uniform on the effect.
  32382. * @param {string} name Name of the sampler.
  32383. * @param {Texture} texture
  32384. */
  32385. UniformBuffer.prototype.setTexture = function (name, texture) {
  32386. this._currentEffect.setTexture(name, texture);
  32387. };
  32388. /**
  32389. * Directly updates the value of the uniform in the cache AND on the GPU.
  32390. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32391. * @param {number[]|Float32Array} data Flattened data
  32392. */
  32393. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32394. this.updateUniform(uniformName, data, data.length);
  32395. this.update();
  32396. };
  32397. /**
  32398. * Binds this uniform buffer to an effect.
  32399. * @param {Effect} effect
  32400. * @param {string} name Name of the uniform block in the shader.
  32401. */
  32402. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32403. this._currentEffect = effect;
  32404. if (this._noUBO || !this._buffer) {
  32405. return;
  32406. }
  32407. effect.bindUniformBuffer(this._buffer, name);
  32408. };
  32409. /**
  32410. * Disposes the uniform buffer.
  32411. */
  32412. UniformBuffer.prototype.dispose = function () {
  32413. if (this._noUBO) {
  32414. return;
  32415. }
  32416. var index = this._engine._uniformBuffers.indexOf(this);
  32417. if (index !== -1) {
  32418. this._engine._uniformBuffers.splice(index, 1);
  32419. }
  32420. if (!this._buffer) {
  32421. return;
  32422. }
  32423. if (this._engine._releaseBuffer(this._buffer)) {
  32424. this._buffer = null;
  32425. }
  32426. };
  32427. // Pool for avoiding memory leaks
  32428. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32429. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32430. return UniformBuffer;
  32431. }());
  32432. BABYLON.UniformBuffer = UniformBuffer;
  32433. })(BABYLON || (BABYLON = {}));
  32434. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32435. var BABYLON;
  32436. (function (BABYLON) {
  32437. var VertexData = /** @class */ (function () {
  32438. function VertexData() {
  32439. }
  32440. VertexData.prototype.set = function (data, kind) {
  32441. switch (kind) {
  32442. case BABYLON.VertexBuffer.PositionKind:
  32443. this.positions = data;
  32444. break;
  32445. case BABYLON.VertexBuffer.NormalKind:
  32446. this.normals = data;
  32447. break;
  32448. case BABYLON.VertexBuffer.TangentKind:
  32449. this.tangents = data;
  32450. break;
  32451. case BABYLON.VertexBuffer.UVKind:
  32452. this.uvs = data;
  32453. break;
  32454. case BABYLON.VertexBuffer.UV2Kind:
  32455. this.uvs2 = data;
  32456. break;
  32457. case BABYLON.VertexBuffer.UV3Kind:
  32458. this.uvs3 = data;
  32459. break;
  32460. case BABYLON.VertexBuffer.UV4Kind:
  32461. this.uvs4 = data;
  32462. break;
  32463. case BABYLON.VertexBuffer.UV5Kind:
  32464. this.uvs5 = data;
  32465. break;
  32466. case BABYLON.VertexBuffer.UV6Kind:
  32467. this.uvs6 = data;
  32468. break;
  32469. case BABYLON.VertexBuffer.ColorKind:
  32470. this.colors = data;
  32471. break;
  32472. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32473. this.matricesIndices = data;
  32474. break;
  32475. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32476. this.matricesWeights = data;
  32477. break;
  32478. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32479. this.matricesIndicesExtra = data;
  32480. break;
  32481. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32482. this.matricesWeightsExtra = data;
  32483. break;
  32484. }
  32485. };
  32486. /**
  32487. * Associates the vertexData to the passed Mesh.
  32488. * Sets it as updatable or not (default `false`).
  32489. * Returns the VertexData.
  32490. */
  32491. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32492. this._applyTo(mesh, updatable);
  32493. return this;
  32494. };
  32495. /**
  32496. * Associates the vertexData to the passed Geometry.
  32497. * Sets it as updatable or not (default `false`).
  32498. * Returns the VertexData.
  32499. */
  32500. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32501. this._applyTo(geometry, updatable);
  32502. return this;
  32503. };
  32504. /**
  32505. * Updates the associated mesh.
  32506. * Returns the VertexData.
  32507. */
  32508. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32509. this._update(mesh);
  32510. return this;
  32511. };
  32512. /**
  32513. * Updates the associated geometry.
  32514. * Returns the VertexData.
  32515. */
  32516. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32517. this._update(geometry);
  32518. return this;
  32519. };
  32520. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32521. if (updatable === void 0) { updatable = false; }
  32522. if (this.positions) {
  32523. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32524. }
  32525. if (this.normals) {
  32526. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32527. }
  32528. if (this.tangents) {
  32529. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32530. }
  32531. if (this.uvs) {
  32532. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32533. }
  32534. if (this.uvs2) {
  32535. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32536. }
  32537. if (this.uvs3) {
  32538. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32539. }
  32540. if (this.uvs4) {
  32541. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32542. }
  32543. if (this.uvs5) {
  32544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32545. }
  32546. if (this.uvs6) {
  32547. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32548. }
  32549. if (this.colors) {
  32550. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32551. }
  32552. if (this.matricesIndices) {
  32553. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32554. }
  32555. if (this.matricesWeights) {
  32556. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32557. }
  32558. if (this.matricesIndicesExtra) {
  32559. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32560. }
  32561. if (this.matricesWeightsExtra) {
  32562. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32563. }
  32564. if (this.indices) {
  32565. meshOrGeometry.setIndices(this.indices, null, updatable);
  32566. }
  32567. return this;
  32568. };
  32569. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32570. if (this.positions) {
  32571. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32572. }
  32573. if (this.normals) {
  32574. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32575. }
  32576. if (this.tangents) {
  32577. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32578. }
  32579. if (this.uvs) {
  32580. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32581. }
  32582. if (this.uvs2) {
  32583. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32584. }
  32585. if (this.uvs3) {
  32586. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32587. }
  32588. if (this.uvs4) {
  32589. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32590. }
  32591. if (this.uvs5) {
  32592. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32593. }
  32594. if (this.uvs6) {
  32595. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32596. }
  32597. if (this.colors) {
  32598. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32599. }
  32600. if (this.matricesIndices) {
  32601. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32602. }
  32603. if (this.matricesWeights) {
  32604. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32605. }
  32606. if (this.matricesIndicesExtra) {
  32607. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32608. }
  32609. if (this.matricesWeightsExtra) {
  32610. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32611. }
  32612. if (this.indices) {
  32613. meshOrGeometry.setIndices(this.indices, null);
  32614. }
  32615. return this;
  32616. };
  32617. /**
  32618. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32619. * Returns the VertexData.
  32620. */
  32621. VertexData.prototype.transform = function (matrix) {
  32622. var transformed = BABYLON.Vector3.Zero();
  32623. var index;
  32624. if (this.positions) {
  32625. var position = BABYLON.Vector3.Zero();
  32626. for (index = 0; index < this.positions.length; index += 3) {
  32627. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32628. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32629. this.positions[index] = transformed.x;
  32630. this.positions[index + 1] = transformed.y;
  32631. this.positions[index + 2] = transformed.z;
  32632. }
  32633. }
  32634. if (this.normals) {
  32635. var normal = BABYLON.Vector3.Zero();
  32636. for (index = 0; index < this.normals.length; index += 3) {
  32637. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32638. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32639. this.normals[index] = transformed.x;
  32640. this.normals[index + 1] = transformed.y;
  32641. this.normals[index + 2] = transformed.z;
  32642. }
  32643. }
  32644. if (this.tangents) {
  32645. var tangent = BABYLON.Vector4.Zero();
  32646. var tangentTransformed = BABYLON.Vector4.Zero();
  32647. for (index = 0; index < this.tangents.length; index += 4) {
  32648. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32649. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32650. this.tangents[index] = tangentTransformed.x;
  32651. this.tangents[index + 1] = tangentTransformed.y;
  32652. this.tangents[index + 2] = tangentTransformed.z;
  32653. this.tangents[index + 3] = tangentTransformed.w;
  32654. }
  32655. }
  32656. return this;
  32657. };
  32658. /**
  32659. * Merges the passed VertexData into the current one.
  32660. * Returns the modified VertexData.
  32661. */
  32662. VertexData.prototype.merge = function (other) {
  32663. this._validate();
  32664. other._validate();
  32665. if (!this.normals !== !other.normals ||
  32666. !this.tangents !== !other.tangents ||
  32667. !this.uvs !== !other.uvs ||
  32668. !this.uvs2 !== !other.uvs2 ||
  32669. !this.uvs3 !== !other.uvs3 ||
  32670. !this.uvs4 !== !other.uvs4 ||
  32671. !this.uvs5 !== !other.uvs5 ||
  32672. !this.uvs6 !== !other.uvs6 ||
  32673. !this.colors !== !other.colors ||
  32674. !this.matricesIndices !== !other.matricesIndices ||
  32675. !this.matricesWeights !== !other.matricesWeights ||
  32676. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32677. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32678. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32679. }
  32680. if (other.indices) {
  32681. if (!this.indices) {
  32682. this.indices = [];
  32683. }
  32684. var offset = this.positions ? this.positions.length / 3 : 0;
  32685. for (var index = 0; index < other.indices.length; index++) {
  32686. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32687. this.indices.push(other.indices[index] + offset);
  32688. }
  32689. }
  32690. this.positions = this._mergeElement(this.positions, other.positions);
  32691. this.normals = this._mergeElement(this.normals, other.normals);
  32692. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32693. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32694. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32695. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32696. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32697. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32698. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32699. this.colors = this._mergeElement(this.colors, other.colors);
  32700. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32701. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32702. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32703. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32704. return this;
  32705. };
  32706. VertexData.prototype._mergeElement = function (source, other) {
  32707. if (!source) {
  32708. return other;
  32709. }
  32710. if (!other) {
  32711. return source;
  32712. }
  32713. var len = other.length + source.length;
  32714. var isSrcTypedArray = source instanceof Float32Array;
  32715. var isOthTypedArray = other instanceof Float32Array;
  32716. // use non-loop method when the source is Float32Array
  32717. if (isSrcTypedArray) {
  32718. var ret32 = new Float32Array(len);
  32719. ret32.set(source);
  32720. ret32.set(other, source.length);
  32721. return ret32;
  32722. // source is number[], when other is also use concat
  32723. }
  32724. else if (!isOthTypedArray) {
  32725. return source.concat(other);
  32726. // source is a number[], but other is a Float32Array, loop required
  32727. }
  32728. else {
  32729. var ret = source.slice(0); // copy source to a separate array
  32730. for (var i = 0, len = other.length; i < len; i++) {
  32731. ret.push(other[i]);
  32732. }
  32733. return ret;
  32734. }
  32735. };
  32736. VertexData.prototype._validate = function () {
  32737. if (!this.positions) {
  32738. throw new Error("Positions are required");
  32739. }
  32740. var getElementCount = function (kind, values) {
  32741. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32742. if ((values.length % stride) !== 0) {
  32743. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32744. }
  32745. return values.length / stride;
  32746. };
  32747. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32748. var validateElementCount = function (kind, values) {
  32749. var elementCount = getElementCount(kind, values);
  32750. if (elementCount !== positionsElementCount) {
  32751. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32752. }
  32753. };
  32754. if (this.normals)
  32755. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32756. if (this.tangents)
  32757. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32758. if (this.uvs)
  32759. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32760. if (this.uvs2)
  32761. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32762. if (this.uvs3)
  32763. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32764. if (this.uvs4)
  32765. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32766. if (this.uvs5)
  32767. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32768. if (this.uvs6)
  32769. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32770. if (this.colors)
  32771. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32772. if (this.matricesIndices)
  32773. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32774. if (this.matricesWeights)
  32775. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32776. if (this.matricesIndicesExtra)
  32777. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32778. if (this.matricesWeightsExtra)
  32779. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32780. };
  32781. /**
  32782. * Serializes the VertexData.
  32783. * Returns a serialized object.
  32784. */
  32785. VertexData.prototype.serialize = function () {
  32786. var serializationObject = this.serialize();
  32787. if (this.positions) {
  32788. serializationObject.positions = this.positions;
  32789. }
  32790. if (this.normals) {
  32791. serializationObject.normals = this.normals;
  32792. }
  32793. if (this.tangents) {
  32794. serializationObject.tangents = this.tangents;
  32795. }
  32796. if (this.uvs) {
  32797. serializationObject.uvs = this.uvs;
  32798. }
  32799. if (this.uvs2) {
  32800. serializationObject.uvs2 = this.uvs2;
  32801. }
  32802. if (this.uvs3) {
  32803. serializationObject.uvs3 = this.uvs3;
  32804. }
  32805. if (this.uvs4) {
  32806. serializationObject.uvs4 = this.uvs4;
  32807. }
  32808. if (this.uvs5) {
  32809. serializationObject.uvs5 = this.uvs5;
  32810. }
  32811. if (this.uvs6) {
  32812. serializationObject.uvs6 = this.uvs6;
  32813. }
  32814. if (this.colors) {
  32815. serializationObject.colors = this.colors;
  32816. }
  32817. if (this.matricesIndices) {
  32818. serializationObject.matricesIndices = this.matricesIndices;
  32819. serializationObject.matricesIndices._isExpanded = true;
  32820. }
  32821. if (this.matricesWeights) {
  32822. serializationObject.matricesWeights = this.matricesWeights;
  32823. }
  32824. if (this.matricesIndicesExtra) {
  32825. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32826. serializationObject.matricesIndicesExtra._isExpanded = true;
  32827. }
  32828. if (this.matricesWeightsExtra) {
  32829. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32830. }
  32831. serializationObject.indices = this.indices;
  32832. return serializationObject;
  32833. };
  32834. // Statics
  32835. /**
  32836. * Returns the object VertexData associated to the passed mesh.
  32837. */
  32838. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32839. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32840. };
  32841. /**
  32842. * Returns the object VertexData associated to the passed geometry.
  32843. */
  32844. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32845. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32846. };
  32847. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32848. var result = new VertexData();
  32849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32850. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32851. }
  32852. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32853. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32854. }
  32855. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32856. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32857. }
  32858. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32859. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32860. }
  32861. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32862. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32863. }
  32864. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32865. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32866. }
  32867. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32868. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32869. }
  32870. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32871. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32872. }
  32873. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32874. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32875. }
  32876. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32877. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32878. }
  32879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32880. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32881. }
  32882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32883. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32884. }
  32885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32886. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32887. }
  32888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32889. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32890. }
  32891. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32892. return result;
  32893. };
  32894. /**
  32895. * Creates the vertexData of the Ribbon.
  32896. */
  32897. VertexData.CreateRibbon = function (options) {
  32898. var pathArray = options.pathArray;
  32899. var closeArray = options.closeArray || false;
  32900. var closePath = options.closePath || false;
  32901. var invertUV = options.invertUV || false;
  32902. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32903. var offset = options.offset || defaultOffset;
  32904. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32905. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32906. var customUV = options.uvs;
  32907. var customColors = options.colors;
  32908. var positions = [];
  32909. var indices = [];
  32910. var normals = [];
  32911. var uvs = [];
  32912. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32913. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32914. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32915. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32916. var minlg; // minimal length among all paths from pathArray
  32917. var lg = []; // array of path lengths : nb of vertex per path
  32918. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32919. var p; // path iterator
  32920. var i; // point iterator
  32921. var j; // point iterator
  32922. // if single path in pathArray
  32923. if (pathArray.length < 2) {
  32924. var ar1 = [];
  32925. var ar2 = [];
  32926. for (i = 0; i < pathArray[0].length - offset; i++) {
  32927. ar1.push(pathArray[0][i]);
  32928. ar2.push(pathArray[0][i + offset]);
  32929. }
  32930. pathArray = [ar1, ar2];
  32931. }
  32932. // positions and horizontal distances (u)
  32933. var idc = 0;
  32934. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32935. var path;
  32936. var l;
  32937. minlg = pathArray[0].length;
  32938. var vectlg;
  32939. var dist;
  32940. for (p = 0; p < pathArray.length; p++) {
  32941. uTotalDistance[p] = 0;
  32942. us[p] = [0];
  32943. path = pathArray[p];
  32944. l = path.length;
  32945. minlg = (minlg < l) ? minlg : l;
  32946. j = 0;
  32947. while (j < l) {
  32948. positions.push(path[j].x, path[j].y, path[j].z);
  32949. if (j > 0) {
  32950. vectlg = path[j].subtract(path[j - 1]).length();
  32951. dist = vectlg + uTotalDistance[p];
  32952. us[p].push(dist);
  32953. uTotalDistance[p] = dist;
  32954. }
  32955. j++;
  32956. }
  32957. if (closePath) {
  32958. j--;
  32959. positions.push(path[0].x, path[0].y, path[0].z);
  32960. vectlg = path[j].subtract(path[0]).length();
  32961. dist = vectlg + uTotalDistance[p];
  32962. us[p].push(dist);
  32963. uTotalDistance[p] = dist;
  32964. }
  32965. lg[p] = l + closePathCorr;
  32966. idx[p] = idc;
  32967. idc += (l + closePathCorr);
  32968. }
  32969. // vertical distances (v)
  32970. var path1;
  32971. var path2;
  32972. var vertex1 = null;
  32973. var vertex2 = null;
  32974. for (i = 0; i < minlg + closePathCorr; i++) {
  32975. vTotalDistance[i] = 0;
  32976. vs[i] = [0];
  32977. for (p = 0; p < pathArray.length - 1; p++) {
  32978. path1 = pathArray[p];
  32979. path2 = pathArray[p + 1];
  32980. if (i === minlg) {
  32981. vertex1 = path1[0];
  32982. vertex2 = path2[0];
  32983. }
  32984. else {
  32985. vertex1 = path1[i];
  32986. vertex2 = path2[i];
  32987. }
  32988. vectlg = vertex2.subtract(vertex1).length();
  32989. dist = vectlg + vTotalDistance[i];
  32990. vs[i].push(dist);
  32991. vTotalDistance[i] = dist;
  32992. }
  32993. if (closeArray && vertex2 && vertex1) {
  32994. path1 = pathArray[p];
  32995. path2 = pathArray[0];
  32996. if (i === minlg) {
  32997. vertex2 = path2[0];
  32998. }
  32999. vectlg = vertex2.subtract(vertex1).length();
  33000. dist = vectlg + vTotalDistance[i];
  33001. vTotalDistance[i] = dist;
  33002. }
  33003. }
  33004. // uvs
  33005. var u;
  33006. var v;
  33007. if (customUV) {
  33008. for (p = 0; p < customUV.length; p++) {
  33009. uvs.push(customUV[p].x, customUV[p].y);
  33010. }
  33011. }
  33012. else {
  33013. for (p = 0; p < pathArray.length; p++) {
  33014. for (i = 0; i < minlg + closePathCorr; i++) {
  33015. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33016. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33017. if (invertUV) {
  33018. uvs.push(v, u);
  33019. }
  33020. else {
  33021. uvs.push(u, v);
  33022. }
  33023. }
  33024. }
  33025. }
  33026. // indices
  33027. p = 0; // path index
  33028. var pi = 0; // positions array index
  33029. var l1 = lg[p] - 1; // path1 length
  33030. var l2 = lg[p + 1] - 1; // path2 length
  33031. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33032. var shft = idx[1] - idx[0]; // shift
  33033. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33034. while (pi <= min && p < path1nb) {
  33035. // 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
  33036. indices.push(pi, pi + shft, pi + 1);
  33037. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33038. pi += 1;
  33039. if (pi === min) {
  33040. p++;
  33041. if (p === lg.length - 1) {
  33042. shft = idx[0] - idx[p];
  33043. l1 = lg[p] - 1;
  33044. l2 = lg[0] - 1;
  33045. }
  33046. else {
  33047. shft = idx[p + 1] - idx[p];
  33048. l1 = lg[p] - 1;
  33049. l2 = lg[p + 1] - 1;
  33050. }
  33051. pi = idx[p];
  33052. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33053. }
  33054. }
  33055. // normals
  33056. VertexData.ComputeNormals(positions, indices, normals);
  33057. if (closePath) {
  33058. var indexFirst = 0;
  33059. var indexLast = 0;
  33060. for (p = 0; p < pathArray.length; p++) {
  33061. indexFirst = idx[p] * 3;
  33062. if (p + 1 < pathArray.length) {
  33063. indexLast = (idx[p + 1] - 1) * 3;
  33064. }
  33065. else {
  33066. indexLast = normals.length - 3;
  33067. }
  33068. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33069. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33070. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33071. normals[indexLast] = normals[indexFirst];
  33072. normals[indexLast + 1] = normals[indexFirst + 1];
  33073. normals[indexLast + 2] = normals[indexFirst + 2];
  33074. }
  33075. }
  33076. // sides
  33077. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33078. // Colors
  33079. var colors = null;
  33080. if (customColors) {
  33081. colors = new Float32Array(customColors.length * 4);
  33082. for (var c = 0; c < customColors.length; c++) {
  33083. colors[c * 4] = customColors[c].r;
  33084. colors[c * 4 + 1] = customColors[c].g;
  33085. colors[c * 4 + 2] = customColors[c].b;
  33086. colors[c * 4 + 3] = customColors[c].a;
  33087. }
  33088. }
  33089. // Result
  33090. var vertexData = new VertexData();
  33091. var positions32 = new Float32Array(positions);
  33092. var normals32 = new Float32Array(normals);
  33093. var uvs32 = new Float32Array(uvs);
  33094. vertexData.indices = indices;
  33095. vertexData.positions = positions32;
  33096. vertexData.normals = normals32;
  33097. vertexData.uvs = uvs32;
  33098. if (colors) {
  33099. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33100. }
  33101. if (closePath) {
  33102. vertexData._idx = idx;
  33103. }
  33104. return vertexData;
  33105. };
  33106. /**
  33107. * Creates the VertexData of the Box.
  33108. */
  33109. VertexData.CreateBox = function (options) {
  33110. var normalsSource = [
  33111. new BABYLON.Vector3(0, 0, 1),
  33112. new BABYLON.Vector3(0, 0, -1),
  33113. new BABYLON.Vector3(1, 0, 0),
  33114. new BABYLON.Vector3(-1, 0, 0),
  33115. new BABYLON.Vector3(0, 1, 0),
  33116. new BABYLON.Vector3(0, -1, 0)
  33117. ];
  33118. var indices = [];
  33119. var positions = [];
  33120. var normals = [];
  33121. var uvs = [];
  33122. var width = options.width || options.size || 1;
  33123. var height = options.height || options.size || 1;
  33124. var depth = options.depth || options.size || 1;
  33125. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33126. var faceUV = options.faceUV || new Array(6);
  33127. var faceColors = options.faceColors;
  33128. var colors = [];
  33129. // default face colors and UV if undefined
  33130. for (var f = 0; f < 6; f++) {
  33131. if (faceUV[f] === undefined) {
  33132. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33133. }
  33134. if (faceColors && faceColors[f] === undefined) {
  33135. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33136. }
  33137. }
  33138. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33139. // Create each face in turn.
  33140. for (var index = 0; index < normalsSource.length; index++) {
  33141. var normal = normalsSource[index];
  33142. // Get two vectors perpendicular to the face normal and to each other.
  33143. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33144. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33145. // Six indices (two triangles) per face.
  33146. var verticesLength = positions.length / 3;
  33147. indices.push(verticesLength);
  33148. indices.push(verticesLength + 1);
  33149. indices.push(verticesLength + 2);
  33150. indices.push(verticesLength);
  33151. indices.push(verticesLength + 2);
  33152. indices.push(verticesLength + 3);
  33153. // Four vertices per face.
  33154. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33155. positions.push(vertex.x, vertex.y, vertex.z);
  33156. normals.push(normal.x, normal.y, normal.z);
  33157. uvs.push(faceUV[index].z, faceUV[index].w);
  33158. if (faceColors) {
  33159. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33160. }
  33161. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33162. positions.push(vertex.x, vertex.y, vertex.z);
  33163. normals.push(normal.x, normal.y, normal.z);
  33164. uvs.push(faceUV[index].x, faceUV[index].w);
  33165. if (faceColors) {
  33166. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33167. }
  33168. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33169. positions.push(vertex.x, vertex.y, vertex.z);
  33170. normals.push(normal.x, normal.y, normal.z);
  33171. uvs.push(faceUV[index].x, faceUV[index].y);
  33172. if (faceColors) {
  33173. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33174. }
  33175. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33176. positions.push(vertex.x, vertex.y, vertex.z);
  33177. normals.push(normal.x, normal.y, normal.z);
  33178. uvs.push(faceUV[index].z, faceUV[index].y);
  33179. if (faceColors) {
  33180. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33181. }
  33182. }
  33183. // sides
  33184. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33185. // Result
  33186. var vertexData = new VertexData();
  33187. vertexData.indices = indices;
  33188. vertexData.positions = positions;
  33189. vertexData.normals = normals;
  33190. vertexData.uvs = uvs;
  33191. if (faceColors) {
  33192. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33193. vertexData.colors = totalColors;
  33194. }
  33195. return vertexData;
  33196. };
  33197. /**
  33198. * Creates the VertexData of the Sphere.
  33199. */
  33200. VertexData.CreateSphere = function (options) {
  33201. var segments = options.segments || 32;
  33202. var diameterX = options.diameterX || options.diameter || 1;
  33203. var diameterY = options.diameterY || options.diameter || 1;
  33204. var diameterZ = options.diameterZ || options.diameter || 1;
  33205. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33206. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33207. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33208. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33209. var totalZRotationSteps = 2 + segments;
  33210. var totalYRotationSteps = 2 * totalZRotationSteps;
  33211. var indices = [];
  33212. var positions = [];
  33213. var normals = [];
  33214. var uvs = [];
  33215. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33216. var normalizedZ = zRotationStep / totalZRotationSteps;
  33217. var angleZ = normalizedZ * Math.PI * slice;
  33218. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33219. var normalizedY = yRotationStep / totalYRotationSteps;
  33220. var angleY = normalizedY * Math.PI * 2 * arc;
  33221. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33222. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33223. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33224. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33225. var vertex = complete.multiply(radius);
  33226. var normal = complete.divide(radius).normalize();
  33227. positions.push(vertex.x, vertex.y, vertex.z);
  33228. normals.push(normal.x, normal.y, normal.z);
  33229. uvs.push(normalizedY, normalizedZ);
  33230. }
  33231. if (zRotationStep > 0) {
  33232. var verticesCount = positions.length / 3;
  33233. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33234. indices.push((firstIndex));
  33235. indices.push((firstIndex + 1));
  33236. indices.push(firstIndex + totalYRotationSteps + 1);
  33237. indices.push((firstIndex + totalYRotationSteps + 1));
  33238. indices.push((firstIndex + 1));
  33239. indices.push((firstIndex + totalYRotationSteps + 2));
  33240. }
  33241. }
  33242. }
  33243. // Sides
  33244. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33245. // Result
  33246. var vertexData = new VertexData();
  33247. vertexData.indices = indices;
  33248. vertexData.positions = positions;
  33249. vertexData.normals = normals;
  33250. vertexData.uvs = uvs;
  33251. return vertexData;
  33252. };
  33253. /**
  33254. * Creates the VertexData of the Cylinder or Cone.
  33255. */
  33256. VertexData.CreateCylinder = function (options) {
  33257. var height = options.height || 2;
  33258. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33259. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33260. var tessellation = options.tessellation || 24;
  33261. var subdivisions = options.subdivisions || 1;
  33262. var hasRings = options.hasRings ? true : false;
  33263. var enclose = options.enclose ? true : false;
  33264. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33266. var faceUV = options.faceUV || new Array(3);
  33267. var faceColors = options.faceColors;
  33268. // default face colors and UV if undefined
  33269. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33270. var ringNb = (hasRings) ? subdivisions : 1;
  33271. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33272. var f;
  33273. for (f = 0; f < surfaceNb; f++) {
  33274. if (faceColors && faceColors[f] === undefined) {
  33275. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33276. }
  33277. }
  33278. for (f = 0; f < surfaceNb; f++) {
  33279. if (faceUV && faceUV[f] === undefined) {
  33280. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33281. }
  33282. }
  33283. var indices = new Array();
  33284. var positions = new Array();
  33285. var normals = new Array();
  33286. var uvs = new Array();
  33287. var colors = new Array();
  33288. var angle_step = Math.PI * 2 * arc / tessellation;
  33289. var angle;
  33290. var h;
  33291. var radius;
  33292. var tan = (diameterBottom - diameterTop) / 2 / height;
  33293. var ringVertex = BABYLON.Vector3.Zero();
  33294. var ringNormal = BABYLON.Vector3.Zero();
  33295. var ringFirstVertex = BABYLON.Vector3.Zero();
  33296. var ringFirstNormal = BABYLON.Vector3.Zero();
  33297. var quadNormal = BABYLON.Vector3.Zero();
  33298. var Y = BABYLON.Axis.Y;
  33299. // positions, normals, uvs
  33300. var i;
  33301. var j;
  33302. var r;
  33303. var ringIdx = 1;
  33304. var s = 1; // surface index
  33305. var cs = 0;
  33306. var v = 0;
  33307. for (i = 0; i <= subdivisions; i++) {
  33308. h = i / subdivisions;
  33309. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33310. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33311. for (r = 0; r < ringIdx; r++) {
  33312. if (hasRings) {
  33313. s += r;
  33314. }
  33315. if (enclose) {
  33316. s += 2 * r;
  33317. }
  33318. for (j = 0; j <= tessellation; j++) {
  33319. angle = j * angle_step;
  33320. // position
  33321. ringVertex.x = Math.cos(-angle) * radius;
  33322. ringVertex.y = -height / 2 + h * height;
  33323. ringVertex.z = Math.sin(-angle) * radius;
  33324. // normal
  33325. if (diameterTop === 0 && i === subdivisions) {
  33326. // if no top cap, reuse former normals
  33327. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33328. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33329. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33330. }
  33331. else {
  33332. ringNormal.x = ringVertex.x;
  33333. ringNormal.z = ringVertex.z;
  33334. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33335. ringNormal.normalize();
  33336. }
  33337. // keep first ring vertex values for enclose
  33338. if (j === 0) {
  33339. ringFirstVertex.copyFrom(ringVertex);
  33340. ringFirstNormal.copyFrom(ringNormal);
  33341. }
  33342. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33343. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33344. if (hasRings) {
  33345. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33346. }
  33347. else {
  33348. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33349. }
  33350. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33351. if (faceColors) {
  33352. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33353. }
  33354. }
  33355. // if enclose, add four vertices and their dedicated normals
  33356. if (arc !== 1 && enclose) {
  33357. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33358. positions.push(0, ringVertex.y, 0);
  33359. positions.push(0, ringVertex.y, 0);
  33360. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33361. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33362. quadNormal.normalize();
  33363. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33364. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33365. quadNormal.normalize();
  33366. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33367. if (hasRings) {
  33368. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33369. }
  33370. else {
  33371. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33372. }
  33373. uvs.push(faceUV[s + 1].x, v);
  33374. uvs.push(faceUV[s + 1].z, v);
  33375. if (hasRings) {
  33376. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33377. }
  33378. else {
  33379. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33380. }
  33381. uvs.push(faceUV[s + 2].x, v);
  33382. uvs.push(faceUV[s + 2].z, v);
  33383. if (faceColors) {
  33384. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33385. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33386. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33387. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33388. }
  33389. }
  33390. if (cs !== s) {
  33391. cs = s;
  33392. }
  33393. }
  33394. }
  33395. // indices
  33396. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33397. var s;
  33398. i = 0;
  33399. for (s = 0; s < subdivisions; s++) {
  33400. var i0 = 0;
  33401. var i1 = 0;
  33402. var i2 = 0;
  33403. var i3 = 0;
  33404. for (j = 0; j < tessellation; j++) {
  33405. i0 = i * (e + 1) + j;
  33406. i1 = (i + 1) * (e + 1) + j;
  33407. i2 = i * (e + 1) + (j + 1);
  33408. i3 = (i + 1) * (e + 1) + (j + 1);
  33409. indices.push(i0, i1, i2);
  33410. indices.push(i3, i2, i1);
  33411. }
  33412. if (arc !== 1 && enclose) {
  33413. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33414. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33415. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33416. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33417. }
  33418. i = (hasRings) ? (i + 2) : (i + 1);
  33419. }
  33420. // Caps
  33421. var createCylinderCap = function (isTop) {
  33422. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33423. if (radius === 0) {
  33424. return;
  33425. }
  33426. // Cap positions, normals & uvs
  33427. var angle;
  33428. var circleVector;
  33429. var i;
  33430. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33431. var c = null;
  33432. if (faceColors) {
  33433. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33434. }
  33435. // cap center
  33436. var vbase = positions.length / 3;
  33437. var offset = isTop ? height / 2 : -height / 2;
  33438. var center = new BABYLON.Vector3(0, offset, 0);
  33439. positions.push(center.x, center.y, center.z);
  33440. normals.push(0, isTop ? 1 : -1, 0);
  33441. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33442. if (c) {
  33443. colors.push(c.r, c.g, c.b, c.a);
  33444. }
  33445. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33446. for (i = 0; i <= tessellation; i++) {
  33447. angle = Math.PI * 2 * i * arc / tessellation;
  33448. var cos = Math.cos(-angle);
  33449. var sin = Math.sin(-angle);
  33450. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33451. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33452. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33453. normals.push(0, isTop ? 1 : -1, 0);
  33454. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33455. if (c) {
  33456. colors.push(c.r, c.g, c.b, c.a);
  33457. }
  33458. }
  33459. // Cap indices
  33460. for (i = 0; i < tessellation; i++) {
  33461. if (!isTop) {
  33462. indices.push(vbase);
  33463. indices.push(vbase + (i + 1));
  33464. indices.push(vbase + (i + 2));
  33465. }
  33466. else {
  33467. indices.push(vbase);
  33468. indices.push(vbase + (i + 2));
  33469. indices.push(vbase + (i + 1));
  33470. }
  33471. }
  33472. };
  33473. // add caps to geometry
  33474. createCylinderCap(false);
  33475. createCylinderCap(true);
  33476. // Sides
  33477. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33478. var vertexData = new VertexData();
  33479. vertexData.indices = indices;
  33480. vertexData.positions = positions;
  33481. vertexData.normals = normals;
  33482. vertexData.uvs = uvs;
  33483. if (faceColors) {
  33484. vertexData.colors = colors;
  33485. }
  33486. return vertexData;
  33487. };
  33488. /**
  33489. * Creates the VertexData of the Torus.
  33490. */
  33491. VertexData.CreateTorus = function (options) {
  33492. var indices = [];
  33493. var positions = [];
  33494. var normals = [];
  33495. var uvs = [];
  33496. var diameter = options.diameter || 1;
  33497. var thickness = options.thickness || 0.5;
  33498. var tessellation = options.tessellation || 16;
  33499. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33500. var stride = tessellation + 1;
  33501. for (var i = 0; i <= tessellation; i++) {
  33502. var u = i / tessellation;
  33503. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33504. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33505. for (var j = 0; j <= tessellation; j++) {
  33506. var v = 1 - j / tessellation;
  33507. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33508. var dx = Math.cos(innerAngle);
  33509. var dy = Math.sin(innerAngle);
  33510. // Create a vertex.
  33511. var normal = new BABYLON.Vector3(dx, dy, 0);
  33512. var position = normal.scale(thickness / 2);
  33513. var textureCoordinate = new BABYLON.Vector2(u, v);
  33514. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33515. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33516. positions.push(position.x, position.y, position.z);
  33517. normals.push(normal.x, normal.y, normal.z);
  33518. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33519. // And create indices for two triangles.
  33520. var nextI = (i + 1) % stride;
  33521. var nextJ = (j + 1) % stride;
  33522. indices.push(i * stride + j);
  33523. indices.push(i * stride + nextJ);
  33524. indices.push(nextI * stride + j);
  33525. indices.push(i * stride + nextJ);
  33526. indices.push(nextI * stride + nextJ);
  33527. indices.push(nextI * stride + j);
  33528. }
  33529. }
  33530. // Sides
  33531. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33532. // Result
  33533. var vertexData = new VertexData();
  33534. vertexData.indices = indices;
  33535. vertexData.positions = positions;
  33536. vertexData.normals = normals;
  33537. vertexData.uvs = uvs;
  33538. return vertexData;
  33539. };
  33540. /**
  33541. * Creates the VertexData of the LineSystem.
  33542. */
  33543. VertexData.CreateLineSystem = function (options) {
  33544. var indices = [];
  33545. var positions = [];
  33546. var lines = options.lines;
  33547. var colors = options.colors;
  33548. var vertexColors = [];
  33549. var idx = 0;
  33550. for (var l = 0; l < lines.length; l++) {
  33551. var points = lines[l];
  33552. for (var index = 0; index < points.length; index++) {
  33553. positions.push(points[index].x, points[index].y, points[index].z);
  33554. if (colors) {
  33555. var color = colors[l];
  33556. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33557. }
  33558. if (index > 0) {
  33559. indices.push(idx - 1);
  33560. indices.push(idx);
  33561. }
  33562. idx++;
  33563. }
  33564. }
  33565. var vertexData = new VertexData();
  33566. vertexData.indices = indices;
  33567. vertexData.positions = positions;
  33568. if (colors) {
  33569. vertexData.colors = vertexColors;
  33570. }
  33571. return vertexData;
  33572. };
  33573. /**
  33574. * Create the VertexData of the DashedLines.
  33575. */
  33576. VertexData.CreateDashedLines = function (options) {
  33577. var dashSize = options.dashSize || 3;
  33578. var gapSize = options.gapSize || 1;
  33579. var dashNb = options.dashNb || 200;
  33580. var points = options.points;
  33581. var positions = new Array();
  33582. var indices = new Array();
  33583. var curvect = BABYLON.Vector3.Zero();
  33584. var lg = 0;
  33585. var nb = 0;
  33586. var shft = 0;
  33587. var dashshft = 0;
  33588. var curshft = 0;
  33589. var idx = 0;
  33590. var i = 0;
  33591. for (i = 0; i < points.length - 1; i++) {
  33592. points[i + 1].subtractToRef(points[i], curvect);
  33593. lg += curvect.length();
  33594. }
  33595. shft = lg / dashNb;
  33596. dashshft = dashSize * shft / (dashSize + gapSize);
  33597. for (i = 0; i < points.length - 1; i++) {
  33598. points[i + 1].subtractToRef(points[i], curvect);
  33599. nb = Math.floor(curvect.length() / shft);
  33600. curvect.normalize();
  33601. for (var j = 0; j < nb; j++) {
  33602. curshft = shft * j;
  33603. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33604. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33605. indices.push(idx, idx + 1);
  33606. idx += 2;
  33607. }
  33608. }
  33609. // Result
  33610. var vertexData = new VertexData();
  33611. vertexData.positions = positions;
  33612. vertexData.indices = indices;
  33613. return vertexData;
  33614. };
  33615. /**
  33616. * Creates the VertexData of the Ground.
  33617. */
  33618. VertexData.CreateGround = function (options) {
  33619. var indices = [];
  33620. var positions = [];
  33621. var normals = [];
  33622. var uvs = [];
  33623. var row, col;
  33624. var width = options.width || 1;
  33625. var height = options.height || 1;
  33626. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33627. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33628. for (row = 0; row <= subdivisionsY; row++) {
  33629. for (col = 0; col <= subdivisionsX; col++) {
  33630. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33631. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33632. positions.push(position.x, position.y, position.z);
  33633. normals.push(normal.x, normal.y, normal.z);
  33634. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33635. }
  33636. }
  33637. for (row = 0; row < subdivisionsY; row++) {
  33638. for (col = 0; col < subdivisionsX; col++) {
  33639. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33640. indices.push(col + 1 + row * (subdivisionsX + 1));
  33641. indices.push(col + row * (subdivisionsX + 1));
  33642. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33643. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33644. indices.push(col + row * (subdivisionsX + 1));
  33645. }
  33646. }
  33647. // Result
  33648. var vertexData = new VertexData();
  33649. vertexData.indices = indices;
  33650. vertexData.positions = positions;
  33651. vertexData.normals = normals;
  33652. vertexData.uvs = uvs;
  33653. return vertexData;
  33654. };
  33655. /**
  33656. * Creates the VertexData of the TiledGround.
  33657. */
  33658. VertexData.CreateTiledGround = function (options) {
  33659. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33660. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33661. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33662. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33663. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33664. var precision = options.precision || { w: 1, h: 1 };
  33665. var indices = new Array();
  33666. var positions = new Array();
  33667. var normals = new Array();
  33668. var uvs = new Array();
  33669. var row, col, tileRow, tileCol;
  33670. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33671. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33672. precision.w = (precision.w < 1) ? 1 : precision.w;
  33673. precision.h = (precision.h < 1) ? 1 : precision.h;
  33674. var tileSize = {
  33675. 'w': (xmax - xmin) / subdivisions.w,
  33676. 'h': (zmax - zmin) / subdivisions.h
  33677. };
  33678. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33679. // Indices
  33680. var base = positions.length / 3;
  33681. var rowLength = precision.w + 1;
  33682. for (row = 0; row < precision.h; row++) {
  33683. for (col = 0; col < precision.w; col++) {
  33684. var square = [
  33685. base + col + row * rowLength,
  33686. base + (col + 1) + row * rowLength,
  33687. base + (col + 1) + (row + 1) * rowLength,
  33688. base + col + (row + 1) * rowLength
  33689. ];
  33690. indices.push(square[1]);
  33691. indices.push(square[2]);
  33692. indices.push(square[3]);
  33693. indices.push(square[0]);
  33694. indices.push(square[1]);
  33695. indices.push(square[3]);
  33696. }
  33697. }
  33698. // Position, normals and uvs
  33699. var position = BABYLON.Vector3.Zero();
  33700. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33701. for (row = 0; row <= precision.h; row++) {
  33702. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33703. for (col = 0; col <= precision.w; col++) {
  33704. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33705. position.y = 0;
  33706. positions.push(position.x, position.y, position.z);
  33707. normals.push(normal.x, normal.y, normal.z);
  33708. uvs.push(col / precision.w, row / precision.h);
  33709. }
  33710. }
  33711. }
  33712. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33713. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33714. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33715. }
  33716. }
  33717. // Result
  33718. var vertexData = new VertexData();
  33719. vertexData.indices = indices;
  33720. vertexData.positions = positions;
  33721. vertexData.normals = normals;
  33722. vertexData.uvs = uvs;
  33723. return vertexData;
  33724. };
  33725. /**
  33726. * Creates the VertexData of the Ground designed from a heightmap.
  33727. */
  33728. VertexData.CreateGroundFromHeightMap = function (options) {
  33729. var indices = [];
  33730. var positions = [];
  33731. var normals = [];
  33732. var uvs = [];
  33733. var row, col;
  33734. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33735. // Vertices
  33736. for (row = 0; row <= options.subdivisions; row++) {
  33737. for (col = 0; col <= options.subdivisions; col++) {
  33738. 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));
  33739. // Compute height
  33740. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33741. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33742. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33743. var r = options.buffer[pos] / 255.0;
  33744. var g = options.buffer[pos + 1] / 255.0;
  33745. var b = options.buffer[pos + 2] / 255.0;
  33746. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33747. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33748. // Add vertex
  33749. positions.push(position.x, position.y, position.z);
  33750. normals.push(0, 0, 0);
  33751. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33752. }
  33753. }
  33754. // Indices
  33755. for (row = 0; row < options.subdivisions; row++) {
  33756. for (col = 0; col < options.subdivisions; col++) {
  33757. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33758. indices.push(col + 1 + row * (options.subdivisions + 1));
  33759. indices.push(col + row * (options.subdivisions + 1));
  33760. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33761. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33762. indices.push(col + row * (options.subdivisions + 1));
  33763. }
  33764. }
  33765. // Normals
  33766. VertexData.ComputeNormals(positions, indices, normals);
  33767. // Result
  33768. var vertexData = new VertexData();
  33769. vertexData.indices = indices;
  33770. vertexData.positions = positions;
  33771. vertexData.normals = normals;
  33772. vertexData.uvs = uvs;
  33773. return vertexData;
  33774. };
  33775. /**
  33776. * Creates the VertexData of the Plane.
  33777. */
  33778. VertexData.CreatePlane = function (options) {
  33779. var indices = [];
  33780. var positions = [];
  33781. var normals = [];
  33782. var uvs = [];
  33783. var width = options.width || options.size || 1;
  33784. var height = options.height || options.size || 1;
  33785. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33786. // Vertices
  33787. var halfWidth = width / 2.0;
  33788. var halfHeight = height / 2.0;
  33789. positions.push(-halfWidth, -halfHeight, 0);
  33790. normals.push(0, 0, -1.0);
  33791. uvs.push(0.0, 0.0);
  33792. positions.push(halfWidth, -halfHeight, 0);
  33793. normals.push(0, 0, -1.0);
  33794. uvs.push(1.0, 0.0);
  33795. positions.push(halfWidth, halfHeight, 0);
  33796. normals.push(0, 0, -1.0);
  33797. uvs.push(1.0, 1.0);
  33798. positions.push(-halfWidth, halfHeight, 0);
  33799. normals.push(0, 0, -1.0);
  33800. uvs.push(0.0, 1.0);
  33801. // Indices
  33802. indices.push(0);
  33803. indices.push(1);
  33804. indices.push(2);
  33805. indices.push(0);
  33806. indices.push(2);
  33807. indices.push(3);
  33808. // Sides
  33809. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33810. // Result
  33811. var vertexData = new VertexData();
  33812. vertexData.indices = indices;
  33813. vertexData.positions = positions;
  33814. vertexData.normals = normals;
  33815. vertexData.uvs = uvs;
  33816. return vertexData;
  33817. };
  33818. /**
  33819. * Creates the VertexData of the Disc or regular Polygon.
  33820. */
  33821. VertexData.CreateDisc = function (options) {
  33822. var positions = new Array();
  33823. var indices = new Array();
  33824. var normals = new Array();
  33825. var uvs = new Array();
  33826. var radius = options.radius || 0.5;
  33827. var tessellation = options.tessellation || 64;
  33828. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33829. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33830. // positions and uvs
  33831. positions.push(0, 0, 0); // disc center first
  33832. uvs.push(0.5, 0.5);
  33833. var theta = Math.PI * 2 * arc;
  33834. var step = theta / tessellation;
  33835. for (var a = 0; a < theta; a += step) {
  33836. var x = Math.cos(a);
  33837. var y = Math.sin(a);
  33838. var u = (x + 1) / 2;
  33839. var v = (1 - y) / 2;
  33840. positions.push(radius * x, radius * y, 0);
  33841. uvs.push(u, v);
  33842. }
  33843. if (arc === 1) {
  33844. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33845. uvs.push(uvs[2], uvs[3]);
  33846. }
  33847. //indices
  33848. var vertexNb = positions.length / 3;
  33849. for (var i = 1; i < vertexNb - 1; i++) {
  33850. indices.push(i + 1, 0, i);
  33851. }
  33852. // result
  33853. VertexData.ComputeNormals(positions, indices, normals);
  33854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33855. var vertexData = new VertexData();
  33856. vertexData.indices = indices;
  33857. vertexData.positions = positions;
  33858. vertexData.normals = normals;
  33859. vertexData.uvs = uvs;
  33860. return vertexData;
  33861. };
  33862. /**
  33863. * Re-creates the VertexData of the Polygon for sideOrientation.
  33864. */
  33865. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33866. var faceUV = fUV || new Array(3);
  33867. var faceColors = fColors;
  33868. var colors = [];
  33869. // default face colors and UV if undefined
  33870. for (var f = 0; f < 3; f++) {
  33871. if (faceUV[f] === undefined) {
  33872. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33873. }
  33874. if (faceColors && faceColors[f] === undefined) {
  33875. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33876. }
  33877. }
  33878. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33879. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33880. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33881. var indices = polygon.getIndices();
  33882. // set face colours and textures
  33883. var idx = 0;
  33884. var face = 0;
  33885. for (var index = 0; index < normals.length; index += 3) {
  33886. //Edge Face no. 1
  33887. if (Math.abs(normals[index + 1]) < 0.001) {
  33888. face = 1;
  33889. }
  33890. //Top Face no. 0
  33891. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33892. face = 0;
  33893. }
  33894. //Bottom Face no. 2
  33895. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33896. face = 2;
  33897. }
  33898. idx = index / 3;
  33899. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33900. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33901. if (faceColors) {
  33902. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33903. }
  33904. }
  33905. // sides
  33906. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33907. // Result
  33908. var vertexData = new VertexData();
  33909. vertexData.indices = indices;
  33910. vertexData.positions = positions;
  33911. vertexData.normals = normals;
  33912. vertexData.uvs = uvs;
  33913. if (faceColors) {
  33914. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33915. vertexData.colors = totalColors;
  33916. }
  33917. return vertexData;
  33918. };
  33919. /**
  33920. * Creates the VertexData of the IcoSphere.
  33921. */
  33922. VertexData.CreateIcoSphere = function (options) {
  33923. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33924. var radius = options.radius || 1;
  33925. var flat = (options.flat === undefined) ? true : options.flat;
  33926. var subdivisions = options.subdivisions || 4;
  33927. var radiusX = options.radiusX || radius;
  33928. var radiusY = options.radiusY || radius;
  33929. var radiusZ = options.radiusZ || radius;
  33930. var t = (1 + Math.sqrt(5)) / 2;
  33931. // 12 vertex x,y,z
  33932. var ico_vertices = [
  33933. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33934. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33935. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33936. ];
  33937. // index of 3 vertex makes a face of icopshere
  33938. var ico_indices = [
  33939. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33940. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33941. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33942. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33943. ];
  33944. // vertex for uv have aliased position, not for UV
  33945. var vertices_unalias_id = [
  33946. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33947. // vertex alias
  33948. 0,
  33949. 2,
  33950. 3,
  33951. 3,
  33952. 3,
  33953. 4,
  33954. 7,
  33955. 8,
  33956. 9,
  33957. 9,
  33958. 10,
  33959. 11 // 23: B + 12
  33960. ];
  33961. // uv as integer step (not pixels !)
  33962. var ico_vertexuv = [
  33963. 5, 1, 3, 1, 6, 4, 0, 0,
  33964. 5, 3, 4, 2, 2, 2, 4, 0,
  33965. 2, 0, 1, 1, 6, 0, 6, 2,
  33966. // vertex alias (for same vertex on different faces)
  33967. 0, 4,
  33968. 3, 3,
  33969. 4, 4,
  33970. 3, 1,
  33971. 4, 2,
  33972. 4, 4,
  33973. 0, 2,
  33974. 1, 1,
  33975. 2, 2,
  33976. 3, 3,
  33977. 1, 3,
  33978. 2, 4 // 23: B + 12
  33979. ];
  33980. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33981. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33982. // First island of uv mapping
  33983. // v = 4h 3+ 2
  33984. // v = 3h 9+ 4
  33985. // v = 2h 9+ 5 B
  33986. // v = 1h 9 1 0
  33987. // v = 0h 3 8 7 A
  33988. // u = 0 1 2 3 4 5 6 *a
  33989. // Second island of uv mapping
  33990. // v = 4h 0+ B+ 4+
  33991. // v = 3h A+ 2+
  33992. // v = 2h 7+ 6 3+
  33993. // v = 1h 8+ 3+
  33994. // v = 0h
  33995. // u = 0 1 2 3 4 5 6 *a
  33996. // Face layout on texture UV mapping
  33997. // ============
  33998. // \ 4 /\ 16 / ======
  33999. // \ / \ / /\ 11 /
  34000. // \/ 7 \/ / \ /
  34001. // ======= / 10 \/
  34002. // /\ 17 /\ =======
  34003. // / \ / \ \ 15 /\
  34004. // / 8 \/ 12 \ \ / \
  34005. // ============ \/ 6 \
  34006. // \ 18 /\ ============
  34007. // \ / \ \ 5 /\ 0 /
  34008. // \/ 13 \ \ / \ /
  34009. // ======= \/ 1 \/
  34010. // =============
  34011. // /\ 19 /\ 2 /\
  34012. // / \ / \ / \
  34013. // / 14 \/ 9 \/ 3 \
  34014. // ===================
  34015. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34016. var ustep = 138 / 1024;
  34017. var vstep = 239 / 1024;
  34018. var uoffset = 60 / 1024;
  34019. var voffset = 26 / 1024;
  34020. // Second island should have margin, not to touch the first island
  34021. // avoid any borderline artefact in pixel rounding
  34022. var island_u_offset = -40 / 1024;
  34023. var island_v_offset = +20 / 1024;
  34024. // face is either island 0 or 1 :
  34025. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34026. var island = [
  34027. 0, 0, 0, 0, 1,
  34028. 0, 0, 1, 1, 0,
  34029. 0, 0, 1, 1, 0,
  34030. 0, 1, 1, 1, 0 // 15 - 19
  34031. ];
  34032. var indices = new Array();
  34033. var positions = new Array();
  34034. var normals = new Array();
  34035. var uvs = new Array();
  34036. var current_indice = 0;
  34037. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34038. var face_vertex_pos = new Array(3);
  34039. var face_vertex_uv = new Array(3);
  34040. var v012;
  34041. for (v012 = 0; v012 < 3; v012++) {
  34042. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34043. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34044. }
  34045. // create all with normals
  34046. for (var face = 0; face < 20; face++) {
  34047. // 3 vertex per face
  34048. for (v012 = 0; v012 < 3; v012++) {
  34049. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34050. var v_id = ico_indices[3 * face + v012];
  34051. // vertex have 3D position (x,y,z)
  34052. 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]);
  34053. // Normalize to get normal, then scale to radius
  34054. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34055. // uv Coordinates from vertex ID
  34056. 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);
  34057. }
  34058. // Subdivide the face (interpolate pos, norm, uv)
  34059. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34060. // - norm is linear interpolation of vertex corner normal
  34061. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34062. // - uv is linear interpolation
  34063. //
  34064. // Topology is as below for sub-divide by 2
  34065. // vertex shown as v0,v1,v2
  34066. // interp index is i1 to progress in range [v0,v1[
  34067. // interp index is i2 to progress in range [v0,v2[
  34068. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34069. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34070. //
  34071. //
  34072. // i2 v2
  34073. // ^ ^
  34074. // / / \
  34075. // / / \
  34076. // / / \
  34077. // / / (0,1) \
  34078. // / #---------\
  34079. // / / \ (0,0)'/ \
  34080. // / / \ / \
  34081. // / / \ / \
  34082. // / / (0,0) \ / (1,0) \
  34083. // / #---------#---------\
  34084. // v0 v1
  34085. //
  34086. // --------------------> i1
  34087. //
  34088. // interp of (i1,i2):
  34089. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34090. // along i1 : lerp(x0,x1, i1/(S-i2))
  34091. //
  34092. // centroid of triangle is needed to get help normal computation
  34093. // (c1,c2) are used for centroid location
  34094. var interp_vertex = function (i1, i2, c1, c2) {
  34095. // vertex is interpolated from
  34096. // - face_vertex_pos[0..2]
  34097. // - face_vertex_uv[0..2]
  34098. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34099. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34100. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34101. pos_interp.normalize();
  34102. var vertex_normal;
  34103. if (flat) {
  34104. // in flat mode, recalculate normal as face centroid normal
  34105. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34106. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34107. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34108. }
  34109. else {
  34110. // in smooth mode, recalculate normal from each single vertex position
  34111. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34112. }
  34113. // Vertex normal need correction due to X,Y,Z radius scaling
  34114. vertex_normal.x /= radiusX;
  34115. vertex_normal.y /= radiusY;
  34116. vertex_normal.z /= radiusZ;
  34117. vertex_normal.normalize();
  34118. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34119. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34120. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34121. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34122. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34123. uvs.push(uv_interp.x, uv_interp.y);
  34124. // push each vertex has member of a face
  34125. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34126. indices.push(current_indice);
  34127. current_indice++;
  34128. };
  34129. for (var i2 = 0; i2 < subdivisions; i2++) {
  34130. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34131. // face : (i1,i2) for /\ :
  34132. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34133. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34134. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34135. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34136. if (i1 + i2 + 1 < subdivisions) {
  34137. // face : (i1,i2)' for \/ :
  34138. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34139. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34140. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34141. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34142. }
  34143. }
  34144. }
  34145. }
  34146. // Sides
  34147. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34148. // Result
  34149. var vertexData = new VertexData();
  34150. vertexData.indices = indices;
  34151. vertexData.positions = positions;
  34152. vertexData.normals = normals;
  34153. vertexData.uvs = uvs;
  34154. return vertexData;
  34155. };
  34156. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34157. /**
  34158. * Creates the VertexData of the Polyhedron.
  34159. */
  34160. VertexData.CreatePolyhedron = function (options) {
  34161. // provided polyhedron types :
  34162. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34163. // 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)
  34164. var polyhedra = [];
  34165. 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]] };
  34166. 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]] };
  34167. polyhedra[2] = {
  34168. 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]],
  34169. 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]]
  34170. };
  34171. polyhedra[3] = {
  34172. 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]],
  34173. 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]]
  34174. };
  34175. polyhedra[4] = {
  34176. 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]],
  34177. 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]]
  34178. };
  34179. 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]] };
  34180. 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]] };
  34181. 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]] };
  34182. 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]] };
  34183. 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]] };
  34184. 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]] };
  34185. 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]] };
  34186. 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]] };
  34187. 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]] };
  34188. polyhedra[14] = {
  34189. 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]],
  34190. 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]]
  34191. };
  34192. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34193. var size = options.size;
  34194. var sizeX = options.sizeX || size || 1;
  34195. var sizeY = options.sizeY || size || 1;
  34196. var sizeZ = options.sizeZ || size || 1;
  34197. var data = options.custom || polyhedra[type];
  34198. var nbfaces = data.face.length;
  34199. var faceUV = options.faceUV || new Array(nbfaces);
  34200. var faceColors = options.faceColors;
  34201. var flat = (options.flat === undefined) ? true : options.flat;
  34202. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34203. var positions = new Array();
  34204. var indices = new Array();
  34205. var normals = new Array();
  34206. var uvs = new Array();
  34207. var colors = new Array();
  34208. var index = 0;
  34209. var faceIdx = 0; // face cursor in the array "indexes"
  34210. var indexes = new Array();
  34211. var i = 0;
  34212. var f = 0;
  34213. var u, v, ang, x, y, tmp;
  34214. // default face colors and UV if undefined
  34215. if (flat) {
  34216. for (f = 0; f < nbfaces; f++) {
  34217. if (faceColors && faceColors[f] === undefined) {
  34218. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34219. }
  34220. if (faceUV && faceUV[f] === undefined) {
  34221. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34222. }
  34223. }
  34224. }
  34225. if (!flat) {
  34226. for (i = 0; i < data.vertex.length; i++) {
  34227. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34228. uvs.push(0, 0);
  34229. }
  34230. for (f = 0; f < nbfaces; f++) {
  34231. for (i = 0; i < data.face[f].length - 2; i++) {
  34232. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34233. }
  34234. }
  34235. }
  34236. else {
  34237. for (f = 0; f < nbfaces; f++) {
  34238. var fl = data.face[f].length; // number of vertices of the current face
  34239. ang = 2 * Math.PI / fl;
  34240. x = 0.5 * Math.tan(ang / 2);
  34241. y = 0.5;
  34242. // positions, uvs, colors
  34243. for (i = 0; i < fl; i++) {
  34244. // positions
  34245. 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);
  34246. indexes.push(index);
  34247. index++;
  34248. // uvs
  34249. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34250. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34251. uvs.push(u, v);
  34252. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34253. y = x * Math.sin(ang) + y * Math.cos(ang);
  34254. x = tmp;
  34255. // colors
  34256. if (faceColors) {
  34257. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34258. }
  34259. }
  34260. // indices from indexes
  34261. for (i = 0; i < fl - 2; i++) {
  34262. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34263. }
  34264. faceIdx += fl;
  34265. }
  34266. }
  34267. VertexData.ComputeNormals(positions, indices, normals);
  34268. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34269. var vertexData = new VertexData();
  34270. vertexData.positions = positions;
  34271. vertexData.indices = indices;
  34272. vertexData.normals = normals;
  34273. vertexData.uvs = uvs;
  34274. if (faceColors && flat) {
  34275. vertexData.colors = colors;
  34276. }
  34277. return vertexData;
  34278. };
  34279. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34280. /**
  34281. * Creates the VertexData of the Torus Knot.
  34282. */
  34283. VertexData.CreateTorusKnot = function (options) {
  34284. var indices = new Array();
  34285. var positions = new Array();
  34286. var normals = new Array();
  34287. var uvs = new Array();
  34288. var radius = options.radius || 2;
  34289. var tube = options.tube || 0.5;
  34290. var radialSegments = options.radialSegments || 32;
  34291. var tubularSegments = options.tubularSegments || 32;
  34292. var p = options.p || 2;
  34293. var q = options.q || 3;
  34294. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34295. // Helper
  34296. var getPos = function (angle) {
  34297. var cu = Math.cos(angle);
  34298. var su = Math.sin(angle);
  34299. var quOverP = q / p * angle;
  34300. var cs = Math.cos(quOverP);
  34301. var tx = radius * (2 + cs) * 0.5 * cu;
  34302. var ty = radius * (2 + cs) * su * 0.5;
  34303. var tz = radius * Math.sin(quOverP) * 0.5;
  34304. return new BABYLON.Vector3(tx, ty, tz);
  34305. };
  34306. // Vertices
  34307. var i;
  34308. var j;
  34309. for (i = 0; i <= radialSegments; i++) {
  34310. var modI = i % radialSegments;
  34311. var u = modI / radialSegments * 2 * p * Math.PI;
  34312. var p1 = getPos(u);
  34313. var p2 = getPos(u + 0.01);
  34314. var tang = p2.subtract(p1);
  34315. var n = p2.add(p1);
  34316. var bitan = BABYLON.Vector3.Cross(tang, n);
  34317. n = BABYLON.Vector3.Cross(bitan, tang);
  34318. bitan.normalize();
  34319. n.normalize();
  34320. for (j = 0; j < tubularSegments; j++) {
  34321. var modJ = j % tubularSegments;
  34322. var v = modJ / tubularSegments * 2 * Math.PI;
  34323. var cx = -tube * Math.cos(v);
  34324. var cy = tube * Math.sin(v);
  34325. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34326. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34327. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34328. uvs.push(i / radialSegments);
  34329. uvs.push(j / tubularSegments);
  34330. }
  34331. }
  34332. for (i = 0; i < radialSegments; i++) {
  34333. for (j = 0; j < tubularSegments; j++) {
  34334. var jNext = (j + 1) % tubularSegments;
  34335. var a = i * tubularSegments + j;
  34336. var b = (i + 1) * tubularSegments + j;
  34337. var c = (i + 1) * tubularSegments + jNext;
  34338. var d = i * tubularSegments + jNext;
  34339. indices.push(d);
  34340. indices.push(b);
  34341. indices.push(a);
  34342. indices.push(d);
  34343. indices.push(c);
  34344. indices.push(b);
  34345. }
  34346. }
  34347. // Normals
  34348. VertexData.ComputeNormals(positions, indices, normals);
  34349. // Sides
  34350. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34351. // Result
  34352. var vertexData = new VertexData();
  34353. vertexData.indices = indices;
  34354. vertexData.positions = positions;
  34355. vertexData.normals = normals;
  34356. vertexData.uvs = uvs;
  34357. return vertexData;
  34358. };
  34359. // Tools
  34360. /**
  34361. * @param {any} - positions (number[] or Float32Array)
  34362. * @param {any} - indices (number[] or Uint16Array)
  34363. * @param {any} - normals (number[] or Float32Array)
  34364. * options (optional) :
  34365. * facetPositions : optional array of facet positions (vector3)
  34366. * facetNormals : optional array of facet normals (vector3)
  34367. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34368. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34369. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34370. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34371. * bInfo : optional bounding info, required for facetPartitioning computation
  34372. * useRightHandedSystem: optional boolean to for right handed system computation
  34373. * depthSort : optional boolean to enable the facet depth sort computation
  34374. * distanceTo : optional Vector3 to compute the facet depth from this location
  34375. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34376. */
  34377. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34378. // temporary scalar variables
  34379. var index = 0; // facet index
  34380. var p1p2x = 0.0; // p1p2 vector x coordinate
  34381. var p1p2y = 0.0; // p1p2 vector y coordinate
  34382. var p1p2z = 0.0; // p1p2 vector z coordinate
  34383. var p3p2x = 0.0; // p3p2 vector x coordinate
  34384. var p3p2y = 0.0; // p3p2 vector y coordinate
  34385. var p3p2z = 0.0; // p3p2 vector z coordinate
  34386. var faceNormalx = 0.0; // facet normal x coordinate
  34387. var faceNormaly = 0.0; // facet normal y coordinate
  34388. var faceNormalz = 0.0; // facet normal z coordinate
  34389. var length = 0.0; // facet normal length before normalization
  34390. var v1x = 0; // vector1 x index in the positions array
  34391. var v1y = 0; // vector1 y index in the positions array
  34392. var v1z = 0; // vector1 z index in the positions array
  34393. var v2x = 0; // vector2 x index in the positions array
  34394. var v2y = 0; // vector2 y index in the positions array
  34395. var v2z = 0; // vector2 z index in the positions array
  34396. var v3x = 0; // vector3 x index in the positions array
  34397. var v3y = 0; // vector3 y index in the positions array
  34398. var v3z = 0; // vector3 z index in the positions array
  34399. var computeFacetNormals = false;
  34400. var computeFacetPositions = false;
  34401. var computeFacetPartitioning = false;
  34402. var computeDepthSort = false;
  34403. var faceNormalSign = 1;
  34404. var ratio = 0;
  34405. var distanceTo = null;
  34406. if (options) {
  34407. computeFacetNormals = (options.facetNormals) ? true : false;
  34408. computeFacetPositions = (options.facetPositions) ? true : false;
  34409. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34410. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34411. ratio = options.ratio || 0;
  34412. computeDepthSort = (options.depthSort) ? true : false;
  34413. distanceTo = (options.distanceTo);
  34414. if (computeDepthSort) {
  34415. if (distanceTo === undefined) {
  34416. distanceTo = BABYLON.Vector3.Zero();
  34417. }
  34418. var depthSortedFacets = options.depthSortedFacets;
  34419. }
  34420. }
  34421. // facetPartitioning reinit if needed
  34422. var xSubRatio = 0;
  34423. var ySubRatio = 0;
  34424. var zSubRatio = 0;
  34425. var subSq = 0;
  34426. if (computeFacetPartitioning && options && options.bbSize) {
  34427. var ox = 0; // X partitioning index for facet position
  34428. var oy = 0; // Y partinioning index for facet position
  34429. var oz = 0; // Z partinioning index for facet position
  34430. var b1x = 0; // X partitioning index for facet v1 vertex
  34431. var b1y = 0; // Y partitioning index for facet v1 vertex
  34432. var b1z = 0; // z partitioning index for facet v1 vertex
  34433. var b2x = 0; // X partitioning index for facet v2 vertex
  34434. var b2y = 0; // Y partitioning index for facet v2 vertex
  34435. var b2z = 0; // Z partitioning index for facet v2 vertex
  34436. var b3x = 0; // X partitioning index for facet v3 vertex
  34437. var b3y = 0; // Y partitioning index for facet v3 vertex
  34438. var b3z = 0; // Z partitioning index for facet v3 vertex
  34439. var block_idx_o = 0; // facet barycenter block index
  34440. var block_idx_v1 = 0; // v1 vertex block index
  34441. var block_idx_v2 = 0; // v2 vertex block index
  34442. var block_idx_v3 = 0; // v3 vertex block index
  34443. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34444. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34445. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34446. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34447. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34448. subSq = options.subDiv.max * options.subDiv.max;
  34449. options.facetPartitioning.length = 0;
  34450. }
  34451. // reset the normals
  34452. for (index = 0; index < positions.length; index++) {
  34453. normals[index] = 0.0;
  34454. }
  34455. // Loop : 1 indice triplet = 1 facet
  34456. var nbFaces = (indices.length / 3) | 0;
  34457. for (index = 0; index < nbFaces; index++) {
  34458. // get the indexes of the coordinates of each vertex of the facet
  34459. v1x = indices[index * 3] * 3;
  34460. v1y = v1x + 1;
  34461. v1z = v1x + 2;
  34462. v2x = indices[index * 3 + 1] * 3;
  34463. v2y = v2x + 1;
  34464. v2z = v2x + 2;
  34465. v3x = indices[index * 3 + 2] * 3;
  34466. v3y = v3x + 1;
  34467. v3z = v3x + 2;
  34468. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34469. p1p2y = positions[v1y] - positions[v2y];
  34470. p1p2z = positions[v1z] - positions[v2z];
  34471. p3p2x = positions[v3x] - positions[v2x];
  34472. p3p2y = positions[v3y] - positions[v2y];
  34473. p3p2z = positions[v3z] - positions[v2z];
  34474. // compute the face normal with the cross product
  34475. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34476. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34477. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34478. // normalize this normal and store it in the array facetData
  34479. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34480. length = (length === 0) ? 1.0 : length;
  34481. faceNormalx /= length;
  34482. faceNormaly /= length;
  34483. faceNormalz /= length;
  34484. if (computeFacetNormals && options) {
  34485. options.facetNormals[index].x = faceNormalx;
  34486. options.facetNormals[index].y = faceNormaly;
  34487. options.facetNormals[index].z = faceNormalz;
  34488. }
  34489. if (computeFacetPositions && options) {
  34490. // compute and the facet barycenter coordinates in the array facetPositions
  34491. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34492. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34493. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34494. }
  34495. if (computeFacetPartitioning && options) {
  34496. // store the facet indexes in arrays in the main facetPartitioning array :
  34497. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34498. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34499. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34500. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34501. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34502. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34503. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34504. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34505. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34506. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34507. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34508. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34509. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34510. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34511. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34512. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34513. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34514. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34515. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34516. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34517. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34518. // push each facet index in each block containing the vertex
  34519. options.facetPartitioning[block_idx_v1].push(index);
  34520. if (block_idx_v2 != block_idx_v1) {
  34521. options.facetPartitioning[block_idx_v2].push(index);
  34522. }
  34523. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34524. options.facetPartitioning[block_idx_v3].push(index);
  34525. }
  34526. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34527. options.facetPartitioning[block_idx_o].push(index);
  34528. }
  34529. }
  34530. if (computeDepthSort && options && options.facetPositions) {
  34531. var dsf = depthSortedFacets[index];
  34532. dsf.ind = index * 3;
  34533. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34534. }
  34535. // compute the normals anyway
  34536. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34537. normals[v1y] += faceNormaly;
  34538. normals[v1z] += faceNormalz;
  34539. normals[v2x] += faceNormalx;
  34540. normals[v2y] += faceNormaly;
  34541. normals[v2z] += faceNormalz;
  34542. normals[v3x] += faceNormalx;
  34543. normals[v3y] += faceNormaly;
  34544. normals[v3z] += faceNormalz;
  34545. }
  34546. // last normalization of each normal
  34547. for (index = 0; index < normals.length / 3; index++) {
  34548. faceNormalx = normals[index * 3];
  34549. faceNormaly = normals[index * 3 + 1];
  34550. faceNormalz = normals[index * 3 + 2];
  34551. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34552. length = (length === 0) ? 1.0 : length;
  34553. faceNormalx /= length;
  34554. faceNormaly /= length;
  34555. faceNormalz /= length;
  34556. normals[index * 3] = faceNormalx;
  34557. normals[index * 3 + 1] = faceNormaly;
  34558. normals[index * 3 + 2] = faceNormalz;
  34559. }
  34560. };
  34561. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34562. var li = indices.length;
  34563. var ln = normals.length;
  34564. var i;
  34565. var n;
  34566. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34567. switch (sideOrientation) {
  34568. case BABYLON.Mesh.FRONTSIDE:
  34569. // nothing changed
  34570. break;
  34571. case BABYLON.Mesh.BACKSIDE:
  34572. var tmp;
  34573. // indices
  34574. for (i = 0; i < li; i += 3) {
  34575. tmp = indices[i];
  34576. indices[i] = indices[i + 2];
  34577. indices[i + 2] = tmp;
  34578. }
  34579. // normals
  34580. for (n = 0; n < ln; n++) {
  34581. normals[n] = -normals[n];
  34582. }
  34583. break;
  34584. case BABYLON.Mesh.DOUBLESIDE:
  34585. // positions
  34586. var lp = positions.length;
  34587. var l = lp / 3;
  34588. for (var p = 0; p < lp; p++) {
  34589. positions[lp + p] = positions[p];
  34590. }
  34591. // indices
  34592. for (i = 0; i < li; i += 3) {
  34593. indices[i + li] = indices[i + 2] + l;
  34594. indices[i + 1 + li] = indices[i + 1] + l;
  34595. indices[i + 2 + li] = indices[i] + l;
  34596. }
  34597. // normals
  34598. for (n = 0; n < ln; n++) {
  34599. normals[ln + n] = -normals[n];
  34600. }
  34601. // uvs
  34602. var lu = uvs.length;
  34603. var u = 0;
  34604. for (u = 0; u < lu; u++) {
  34605. uvs[u + lu] = uvs[u];
  34606. }
  34607. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34608. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34609. u = 0;
  34610. for (i = 0; i < lu / 2; i++) {
  34611. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34612. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34613. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34614. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34615. u += 2;
  34616. }
  34617. break;
  34618. }
  34619. };
  34620. /**
  34621. * Creates a new VertexData from the imported parameters.
  34622. */
  34623. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34624. var vertexData = new VertexData();
  34625. // positions
  34626. var positions = parsedVertexData.positions;
  34627. if (positions) {
  34628. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34629. }
  34630. // normals
  34631. var normals = parsedVertexData.normals;
  34632. if (normals) {
  34633. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34634. }
  34635. // tangents
  34636. var tangents = parsedVertexData.tangents;
  34637. if (tangents) {
  34638. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34639. }
  34640. // uvs
  34641. var uvs = parsedVertexData.uvs;
  34642. if (uvs) {
  34643. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34644. }
  34645. // uv2s
  34646. var uv2s = parsedVertexData.uv2s;
  34647. if (uv2s) {
  34648. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34649. }
  34650. // uv3s
  34651. var uv3s = parsedVertexData.uv3s;
  34652. if (uv3s) {
  34653. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34654. }
  34655. // uv4s
  34656. var uv4s = parsedVertexData.uv4s;
  34657. if (uv4s) {
  34658. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34659. }
  34660. // uv5s
  34661. var uv5s = parsedVertexData.uv5s;
  34662. if (uv5s) {
  34663. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34664. }
  34665. // uv6s
  34666. var uv6s = parsedVertexData.uv6s;
  34667. if (uv6s) {
  34668. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34669. }
  34670. // colors
  34671. var colors = parsedVertexData.colors;
  34672. if (colors) {
  34673. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34674. }
  34675. // matricesIndices
  34676. var matricesIndices = parsedVertexData.matricesIndices;
  34677. if (matricesIndices) {
  34678. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34679. }
  34680. // matricesWeights
  34681. var matricesWeights = parsedVertexData.matricesWeights;
  34682. if (matricesWeights) {
  34683. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34684. }
  34685. // indices
  34686. var indices = parsedVertexData.indices;
  34687. if (indices) {
  34688. vertexData.indices = indices;
  34689. }
  34690. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34691. };
  34692. return VertexData;
  34693. }());
  34694. BABYLON.VertexData = VertexData;
  34695. })(BABYLON || (BABYLON = {}));
  34696. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34697. var BABYLON;
  34698. (function (BABYLON) {
  34699. /**
  34700. * Class used to store geometry data (vertex buffers + index buffer)
  34701. */
  34702. var Geometry = /** @class */ (function () {
  34703. /**
  34704. * Creates a new geometry
  34705. * @param id defines the unique ID
  34706. * @param scene defines the hosting scene
  34707. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34708. * @param updatable defines if geometry must be updatable (false by default)
  34709. * @param mesh defines the mesh that will be associated with the geometry
  34710. */
  34711. function Geometry(id, scene, vertexData, updatable, mesh) {
  34712. if (updatable === void 0) { updatable = false; }
  34713. if (mesh === void 0) { mesh = null; }
  34714. /**
  34715. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34716. */
  34717. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34718. this._totalVertices = 0;
  34719. this._isDisposed = false;
  34720. this._indexBufferIsUpdatable = false;
  34721. this.id = id;
  34722. this._engine = scene.getEngine();
  34723. this._meshes = [];
  34724. this._scene = scene;
  34725. //Init vertex buffer cache
  34726. this._vertexBuffers = {};
  34727. this._indices = [];
  34728. this._updatable = updatable;
  34729. // vertexData
  34730. if (vertexData) {
  34731. this.setAllVerticesData(vertexData, updatable);
  34732. }
  34733. else {
  34734. this._totalVertices = 0;
  34735. this._indices = [];
  34736. }
  34737. if (this._engine.getCaps().vertexArrayObject) {
  34738. this._vertexArrayObjects = {};
  34739. }
  34740. // applyToMesh
  34741. if (mesh) {
  34742. if (mesh.getClassName() === "LinesMesh") {
  34743. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34744. this.updateExtend();
  34745. }
  34746. this.applyToMesh(mesh);
  34747. mesh.computeWorldMatrix(true);
  34748. }
  34749. }
  34750. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34751. /**
  34752. * 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
  34753. */
  34754. get: function () {
  34755. return this._boundingBias;
  34756. },
  34757. /**
  34758. * 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
  34759. */
  34760. set: function (value) {
  34761. if (this._boundingBias && this._boundingBias.equals(value)) {
  34762. return;
  34763. }
  34764. this._boundingBias = value.clone();
  34765. this.updateBoundingInfo(true, null);
  34766. },
  34767. enumerable: true,
  34768. configurable: true
  34769. });
  34770. /**
  34771. * Static function used to attach a new empty geometry to a mesh
  34772. * @param mesh defines the mesh to attach the geometry to
  34773. * @returns the new {BABYLON.Geometry}
  34774. */
  34775. Geometry.CreateGeometryForMesh = function (mesh) {
  34776. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34777. geometry.applyToMesh(mesh);
  34778. return geometry;
  34779. };
  34780. Object.defineProperty(Geometry.prototype, "extend", {
  34781. /**
  34782. * Gets the current extend of the geometry
  34783. */
  34784. get: function () {
  34785. return this._extend;
  34786. },
  34787. enumerable: true,
  34788. configurable: true
  34789. });
  34790. /**
  34791. * Gets the hosting scene
  34792. * @returns the hosting {BABYLON.Scene}
  34793. */
  34794. Geometry.prototype.getScene = function () {
  34795. return this._scene;
  34796. };
  34797. /**
  34798. * Gets the hosting engine
  34799. * @returns the hosting {BABYLON.Engine}
  34800. */
  34801. Geometry.prototype.getEngine = function () {
  34802. return this._engine;
  34803. };
  34804. /**
  34805. * Defines if the geometry is ready to use
  34806. * @returns true if the geometry is ready to be used
  34807. */
  34808. Geometry.prototype.isReady = function () {
  34809. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34810. };
  34811. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34812. /**
  34813. * Gets a value indicating that the geometry should not be serialized
  34814. */
  34815. get: function () {
  34816. for (var index = 0; index < this._meshes.length; index++) {
  34817. if (!this._meshes[index].doNotSerialize) {
  34818. return false;
  34819. }
  34820. }
  34821. return true;
  34822. },
  34823. enumerable: true,
  34824. configurable: true
  34825. });
  34826. /** @ignore */
  34827. Geometry.prototype._rebuild = function () {
  34828. if (this._vertexArrayObjects) {
  34829. this._vertexArrayObjects = {};
  34830. }
  34831. // Index buffer
  34832. if (this._meshes.length !== 0 && this._indices) {
  34833. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34834. }
  34835. // Vertex buffers
  34836. for (var key in this._vertexBuffers) {
  34837. var vertexBuffer = this._vertexBuffers[key];
  34838. vertexBuffer._rebuild();
  34839. }
  34840. };
  34841. /**
  34842. * Affects all gemetry data in one call
  34843. * @param vertexData defines the geometry data
  34844. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34845. */
  34846. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34847. vertexData.applyToGeometry(this, updatable);
  34848. this.notifyUpdate();
  34849. };
  34850. /**
  34851. * Set specific vertex data
  34852. * @param kind defines the data kind (Position, normal, etc...)
  34853. * @param data defines the vertex data to use
  34854. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34855. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34856. */
  34857. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34858. if (updatable === void 0) { updatable = false; }
  34859. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34860. this.setVerticesBuffer(buffer);
  34861. };
  34862. /**
  34863. * Removes a specific vertex data
  34864. * @param kind defines the data kind (Position, normal, etc...)
  34865. */
  34866. Geometry.prototype.removeVerticesData = function (kind) {
  34867. if (this._vertexBuffers[kind]) {
  34868. this._vertexBuffers[kind].dispose();
  34869. delete this._vertexBuffers[kind];
  34870. }
  34871. };
  34872. /**
  34873. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34874. * @param buffer defines the vertex buffer to use
  34875. */
  34876. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34877. var kind = buffer.getKind();
  34878. if (this._vertexBuffers[kind]) {
  34879. this._vertexBuffers[kind].dispose();
  34880. }
  34881. this._vertexBuffers[kind] = buffer;
  34882. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34883. var data = buffer.getData();
  34884. var stride = buffer.getStrideSize();
  34885. this._totalVertices = data.length / stride;
  34886. this.updateExtend(data, stride);
  34887. this._resetPointsArrayCache();
  34888. var meshes = this._meshes;
  34889. var numOfMeshes = meshes.length;
  34890. for (var index = 0; index < numOfMeshes; index++) {
  34891. var mesh = meshes[index];
  34892. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34893. mesh._createGlobalSubMesh(false);
  34894. mesh.computeWorldMatrix(true);
  34895. }
  34896. }
  34897. this.notifyUpdate(kind);
  34898. if (this._vertexArrayObjects) {
  34899. this._disposeVertexArrayObjects();
  34900. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34901. }
  34902. };
  34903. /**
  34904. * Update a specific vertex buffer
  34905. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34906. * It will do nothing if the buffer is not updatable
  34907. * @param kind defines the data kind (Position, normal, etc...)
  34908. * @param data defines the data to use
  34909. * @param offset defines the offset in the target buffer where to store the data
  34910. */
  34911. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34912. var vertexBuffer = this.getVertexBuffer(kind);
  34913. if (!vertexBuffer) {
  34914. return;
  34915. }
  34916. vertexBuffer.updateDirectly(data, offset);
  34917. this.notifyUpdate(kind);
  34918. };
  34919. /**
  34920. * Update a specific vertex buffer
  34921. * This function will create a new buffer if the current one is not updatable
  34922. * @param kind defines the data kind (Position, normal, etc...)
  34923. * @param data defines the data to use
  34924. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34925. */
  34926. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34927. if (updateExtends === void 0) { updateExtends = false; }
  34928. var vertexBuffer = this.getVertexBuffer(kind);
  34929. if (!vertexBuffer) {
  34930. return;
  34931. }
  34932. vertexBuffer.update(data);
  34933. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34934. var stride = vertexBuffer.getStrideSize();
  34935. this._totalVertices = data.length / stride;
  34936. this.updateBoundingInfo(updateExtends, data);
  34937. }
  34938. this.notifyUpdate(kind);
  34939. };
  34940. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34941. if (updateExtends) {
  34942. this.updateExtend(data);
  34943. }
  34944. var meshes = this._meshes;
  34945. var numOfMeshes = meshes.length;
  34946. this._resetPointsArrayCache();
  34947. for (var index = 0; index < numOfMeshes; index++) {
  34948. var mesh = meshes[index];
  34949. if (updateExtends) {
  34950. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34951. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34952. var subMesh = mesh.subMeshes[subIndex];
  34953. subMesh.refreshBoundingInfo();
  34954. }
  34955. }
  34956. }
  34957. };
  34958. /** @ignore */
  34959. Geometry.prototype._bind = function (effect, indexToBind) {
  34960. if (!effect) {
  34961. return;
  34962. }
  34963. if (indexToBind === undefined) {
  34964. indexToBind = this._indexBuffer;
  34965. }
  34966. var vbs = this.getVertexBuffers();
  34967. if (!vbs) {
  34968. return;
  34969. }
  34970. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34971. this._engine.bindBuffers(vbs, indexToBind, effect);
  34972. return;
  34973. }
  34974. // Using VAO
  34975. if (!this._vertexArrayObjects[effect.key]) {
  34976. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34977. }
  34978. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34979. };
  34980. /**
  34981. * Gets total number of vertices
  34982. * @returns the total number of vertices
  34983. */
  34984. Geometry.prototype.getTotalVertices = function () {
  34985. if (!this.isReady()) {
  34986. return 0;
  34987. }
  34988. return this._totalVertices;
  34989. };
  34990. /**
  34991. * Gets a specific vertex data attached to this geometry
  34992. * @param kind defines the data kind (Position, normal, etc...)
  34993. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34994. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34995. * @returns a float array containing vertex data
  34996. */
  34997. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34998. var vertexBuffer = this.getVertexBuffer(kind);
  34999. if (!vertexBuffer) {
  35000. return null;
  35001. }
  35002. var orig = vertexBuffer.getData();
  35003. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35004. return orig;
  35005. }
  35006. else {
  35007. var len = orig.length;
  35008. var copy = [];
  35009. for (var i = 0; i < len; i++) {
  35010. copy.push(orig[i]);
  35011. }
  35012. return copy;
  35013. }
  35014. };
  35015. /**
  35016. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35017. * @param kind defines the data kind (Position, normal, etc...)
  35018. * @returns true if the vertex buffer with the specified kind is updatable
  35019. */
  35020. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35021. var vb = this._vertexBuffers[kind];
  35022. if (!vb) {
  35023. return false;
  35024. }
  35025. return vb.isUpdatable();
  35026. };
  35027. /**
  35028. * Gets a specific vertex buffer
  35029. * @param kind defines the data kind (Position, normal, etc...)
  35030. * @returns a {BABYLON.VertexBuffer}
  35031. */
  35032. Geometry.prototype.getVertexBuffer = function (kind) {
  35033. if (!this.isReady()) {
  35034. return null;
  35035. }
  35036. return this._vertexBuffers[kind];
  35037. };
  35038. /**
  35039. * Returns all vertex buffers
  35040. * @return an object holding all vertex buffers indexed by kind
  35041. */
  35042. Geometry.prototype.getVertexBuffers = function () {
  35043. if (!this.isReady()) {
  35044. return null;
  35045. }
  35046. return this._vertexBuffers;
  35047. };
  35048. /**
  35049. * Gets a boolean indicating if specific vertex buffer is present
  35050. * @param kind defines the data kind (Position, normal, etc...)
  35051. * @returns true if data is present
  35052. */
  35053. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35054. if (!this._vertexBuffers) {
  35055. if (this._delayInfo) {
  35056. return this._delayInfo.indexOf(kind) !== -1;
  35057. }
  35058. return false;
  35059. }
  35060. return this._vertexBuffers[kind] !== undefined;
  35061. };
  35062. /**
  35063. * Gets a list of all attached data kinds (Position, normal, etc...)
  35064. * @returns a list of string containing all kinds
  35065. */
  35066. Geometry.prototype.getVerticesDataKinds = function () {
  35067. var result = [];
  35068. var kind;
  35069. if (!this._vertexBuffers && this._delayInfo) {
  35070. for (kind in this._delayInfo) {
  35071. result.push(kind);
  35072. }
  35073. }
  35074. else {
  35075. for (kind in this._vertexBuffers) {
  35076. result.push(kind);
  35077. }
  35078. }
  35079. return result;
  35080. };
  35081. /**
  35082. * Update index buffer
  35083. * @param indices defines the indices to store in the index buffer
  35084. * @param offset defines the offset in the target buffer where to store the data
  35085. */
  35086. Geometry.prototype.updateIndices = function (indices, offset) {
  35087. if (!this._indexBuffer) {
  35088. return;
  35089. }
  35090. if (!this._indexBufferIsUpdatable) {
  35091. this.setIndices(indices, null, true);
  35092. }
  35093. else {
  35094. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35095. }
  35096. };
  35097. /**
  35098. * Creates a new index buffer
  35099. * @param indices defines the indices to store in the index buffer
  35100. * @param totalVertices defines the total number of vertices (could be null)
  35101. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35102. */
  35103. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35104. if (totalVertices === void 0) { totalVertices = null; }
  35105. if (updatable === void 0) { updatable = false; }
  35106. if (this._indexBuffer) {
  35107. this._engine._releaseBuffer(this._indexBuffer);
  35108. }
  35109. this._disposeVertexArrayObjects();
  35110. this._indices = indices;
  35111. this._indexBufferIsUpdatable = updatable;
  35112. if (this._meshes.length !== 0 && this._indices) {
  35113. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35114. }
  35115. if (totalVertices != undefined) {
  35116. this._totalVertices = totalVertices;
  35117. }
  35118. var meshes = this._meshes;
  35119. var numOfMeshes = meshes.length;
  35120. for (var index = 0; index < numOfMeshes; index++) {
  35121. meshes[index]._createGlobalSubMesh(true);
  35122. }
  35123. this.notifyUpdate();
  35124. };
  35125. /**
  35126. * Return the total number of indices
  35127. * @returns the total number of indices
  35128. */
  35129. Geometry.prototype.getTotalIndices = function () {
  35130. if (!this.isReady()) {
  35131. return 0;
  35132. }
  35133. return this._indices.length;
  35134. };
  35135. /**
  35136. * Gets the index buffer array
  35137. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35138. * @returns the index buffer array
  35139. */
  35140. Geometry.prototype.getIndices = function (copyWhenShared) {
  35141. if (!this.isReady()) {
  35142. return null;
  35143. }
  35144. var orig = this._indices;
  35145. if (!copyWhenShared || this._meshes.length === 1) {
  35146. return orig;
  35147. }
  35148. else {
  35149. var len = orig.length;
  35150. var copy = [];
  35151. for (var i = 0; i < len; i++) {
  35152. copy.push(orig[i]);
  35153. }
  35154. return copy;
  35155. }
  35156. };
  35157. /**
  35158. * Gets the index buffer
  35159. * @return the index buffer
  35160. */
  35161. Geometry.prototype.getIndexBuffer = function () {
  35162. if (!this.isReady()) {
  35163. return null;
  35164. }
  35165. return this._indexBuffer;
  35166. };
  35167. /** @ignore */
  35168. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35169. if (effect === void 0) { effect = null; }
  35170. if (!effect || !this._vertexArrayObjects) {
  35171. return;
  35172. }
  35173. if (this._vertexArrayObjects[effect.key]) {
  35174. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35175. delete this._vertexArrayObjects[effect.key];
  35176. }
  35177. };
  35178. /**
  35179. * Release the associated resources for a specific mesh
  35180. * @param mesh defines the source mesh
  35181. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35182. */
  35183. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35184. var meshes = this._meshes;
  35185. var index = meshes.indexOf(mesh);
  35186. if (index === -1) {
  35187. return;
  35188. }
  35189. meshes.splice(index, 1);
  35190. mesh._geometry = null;
  35191. if (meshes.length === 0 && shouldDispose) {
  35192. this.dispose();
  35193. }
  35194. };
  35195. /**
  35196. * Apply current geometry to a given mesh
  35197. * @param mesh defines the mesh to apply geometry to
  35198. */
  35199. Geometry.prototype.applyToMesh = function (mesh) {
  35200. if (mesh._geometry === this) {
  35201. return;
  35202. }
  35203. var previousGeometry = mesh._geometry;
  35204. if (previousGeometry) {
  35205. previousGeometry.releaseForMesh(mesh);
  35206. }
  35207. var meshes = this._meshes;
  35208. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35209. mesh._geometry = this;
  35210. this._scene.pushGeometry(this);
  35211. meshes.push(mesh);
  35212. if (this.isReady()) {
  35213. this._applyToMesh(mesh);
  35214. }
  35215. else {
  35216. mesh._boundingInfo = this._boundingInfo;
  35217. }
  35218. };
  35219. Geometry.prototype.updateExtend = function (data, stride) {
  35220. if (data === void 0) { data = null; }
  35221. if (!data) {
  35222. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35223. }
  35224. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35225. };
  35226. Geometry.prototype._applyToMesh = function (mesh) {
  35227. var numOfMeshes = this._meshes.length;
  35228. // vertexBuffers
  35229. for (var kind in this._vertexBuffers) {
  35230. if (numOfMeshes === 1) {
  35231. this._vertexBuffers[kind].create();
  35232. }
  35233. var buffer = this._vertexBuffers[kind].getBuffer();
  35234. if (buffer)
  35235. buffer.references = numOfMeshes;
  35236. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35237. if (!this._extend) {
  35238. this.updateExtend(this._vertexBuffers[kind].getData());
  35239. }
  35240. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35241. mesh._createGlobalSubMesh(false);
  35242. //bounding info was just created again, world matrix should be applied again.
  35243. mesh._updateBoundingInfo();
  35244. }
  35245. }
  35246. // indexBuffer
  35247. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35248. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35249. }
  35250. if (this._indexBuffer) {
  35251. this._indexBuffer.references = numOfMeshes;
  35252. }
  35253. };
  35254. Geometry.prototype.notifyUpdate = function (kind) {
  35255. if (this.onGeometryUpdated) {
  35256. this.onGeometryUpdated(this, kind);
  35257. }
  35258. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35259. var mesh = _a[_i];
  35260. mesh._markSubMeshesAsAttributesDirty();
  35261. }
  35262. };
  35263. /**
  35264. * Load the geometry if it was flagged as delay loaded
  35265. * @param scene defines the hosting scene
  35266. * @param onLoaded defines a callback called when the geometry is loaded
  35267. */
  35268. Geometry.prototype.load = function (scene, onLoaded) {
  35269. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35270. return;
  35271. }
  35272. if (this.isReady()) {
  35273. if (onLoaded) {
  35274. onLoaded();
  35275. }
  35276. return;
  35277. }
  35278. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35279. this._queueLoad(scene, onLoaded);
  35280. };
  35281. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35282. var _this = this;
  35283. if (!this.delayLoadingFile) {
  35284. return;
  35285. }
  35286. scene._addPendingData(this);
  35287. scene._loadFile(this.delayLoadingFile, function (data) {
  35288. if (!_this._delayLoadingFunction) {
  35289. return;
  35290. }
  35291. _this._delayLoadingFunction(JSON.parse(data), _this);
  35292. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35293. _this._delayInfo = [];
  35294. scene._removePendingData(_this);
  35295. var meshes = _this._meshes;
  35296. var numOfMeshes = meshes.length;
  35297. for (var index = 0; index < numOfMeshes; index++) {
  35298. _this._applyToMesh(meshes[index]);
  35299. }
  35300. if (onLoaded) {
  35301. onLoaded();
  35302. }
  35303. }, undefined, true);
  35304. };
  35305. /**
  35306. * Invert the geometry to move from a right handed system to a left handed one.
  35307. */
  35308. Geometry.prototype.toLeftHanded = function () {
  35309. // Flip faces
  35310. var tIndices = this.getIndices(false);
  35311. if (tIndices != null && tIndices.length > 0) {
  35312. for (var i = 0; i < tIndices.length; i += 3) {
  35313. var tTemp = tIndices[i + 0];
  35314. tIndices[i + 0] = tIndices[i + 2];
  35315. tIndices[i + 2] = tTemp;
  35316. }
  35317. this.setIndices(tIndices);
  35318. }
  35319. // Negate position.z
  35320. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35321. if (tPositions != null && tPositions.length > 0) {
  35322. for (var i = 0; i < tPositions.length; i += 3) {
  35323. tPositions[i + 2] = -tPositions[i + 2];
  35324. }
  35325. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35326. }
  35327. // Negate normal.z
  35328. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35329. if (tNormals != null && tNormals.length > 0) {
  35330. for (var i = 0; i < tNormals.length; i += 3) {
  35331. tNormals[i + 2] = -tNormals[i + 2];
  35332. }
  35333. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35334. }
  35335. };
  35336. // Cache
  35337. /** @ignore */
  35338. Geometry.prototype._resetPointsArrayCache = function () {
  35339. this._positions = null;
  35340. };
  35341. /** @ignore */
  35342. Geometry.prototype._generatePointsArray = function () {
  35343. if (this._positions)
  35344. return true;
  35345. this._positions = [];
  35346. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35347. if (!data) {
  35348. return false;
  35349. }
  35350. for (var index = 0; index < data.length; index += 3) {
  35351. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35352. }
  35353. return true;
  35354. };
  35355. /**
  35356. * Gets a value indicating if the geometry is disposed
  35357. * @returns true if the geometry was disposed
  35358. */
  35359. Geometry.prototype.isDisposed = function () {
  35360. return this._isDisposed;
  35361. };
  35362. Geometry.prototype._disposeVertexArrayObjects = function () {
  35363. if (this._vertexArrayObjects) {
  35364. for (var kind in this._vertexArrayObjects) {
  35365. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35366. }
  35367. this._vertexArrayObjects = {};
  35368. }
  35369. };
  35370. /**
  35371. * Free all associated resources
  35372. */
  35373. Geometry.prototype.dispose = function () {
  35374. var meshes = this._meshes;
  35375. var numOfMeshes = meshes.length;
  35376. var index;
  35377. for (index = 0; index < numOfMeshes; index++) {
  35378. this.releaseForMesh(meshes[index]);
  35379. }
  35380. this._meshes = [];
  35381. this._disposeVertexArrayObjects();
  35382. for (var kind in this._vertexBuffers) {
  35383. this._vertexBuffers[kind].dispose();
  35384. }
  35385. this._vertexBuffers = {};
  35386. this._totalVertices = 0;
  35387. if (this._indexBuffer) {
  35388. this._engine._releaseBuffer(this._indexBuffer);
  35389. }
  35390. this._indexBuffer = null;
  35391. this._indices = [];
  35392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35393. this.delayLoadingFile = null;
  35394. this._delayLoadingFunction = null;
  35395. this._delayInfo = [];
  35396. this._boundingInfo = null;
  35397. this._scene.removeGeometry(this);
  35398. this._isDisposed = true;
  35399. };
  35400. /**
  35401. * Clone the current geometry into a new geometry
  35402. * @param id defines the unique ID of the new geometry
  35403. * @returns a new geometry object
  35404. */
  35405. Geometry.prototype.copy = function (id) {
  35406. var vertexData = new BABYLON.VertexData();
  35407. vertexData.indices = [];
  35408. var indices = this.getIndices();
  35409. if (indices) {
  35410. for (var index = 0; index < indices.length; index++) {
  35411. vertexData.indices.push(indices[index]);
  35412. }
  35413. }
  35414. var updatable = false;
  35415. var stopChecking = false;
  35416. var kind;
  35417. for (kind in this._vertexBuffers) {
  35418. // using slice() to make a copy of the array and not just reference it
  35419. var data = this.getVerticesData(kind);
  35420. if (data instanceof Float32Array) {
  35421. vertexData.set(new Float32Array(data), kind);
  35422. }
  35423. else {
  35424. vertexData.set(data.slice(0), kind);
  35425. }
  35426. if (!stopChecking) {
  35427. var vb = this.getVertexBuffer(kind);
  35428. if (vb) {
  35429. updatable = vb.isUpdatable();
  35430. stopChecking = !updatable;
  35431. }
  35432. }
  35433. }
  35434. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35435. geometry.delayLoadState = this.delayLoadState;
  35436. geometry.delayLoadingFile = this.delayLoadingFile;
  35437. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35438. for (kind in this._delayInfo) {
  35439. geometry._delayInfo = geometry._delayInfo || [];
  35440. geometry._delayInfo.push(kind);
  35441. }
  35442. // Bounding info
  35443. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35444. return geometry;
  35445. };
  35446. /**
  35447. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35448. * @return a JSON representation of the current geometry data (without the vertices data)
  35449. */
  35450. Geometry.prototype.serialize = function () {
  35451. var serializationObject = {};
  35452. serializationObject.id = this.id;
  35453. serializationObject.updatable = this._updatable;
  35454. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35455. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35456. }
  35457. return serializationObject;
  35458. };
  35459. Geometry.prototype.toNumberArray = function (origin) {
  35460. if (Array.isArray(origin)) {
  35461. return origin;
  35462. }
  35463. else {
  35464. return Array.prototype.slice.call(origin);
  35465. }
  35466. };
  35467. /**
  35468. * Serialize all vertices data into a JSON oject
  35469. * @returns a JSON representation of the current geometry data
  35470. */
  35471. Geometry.prototype.serializeVerticeData = function () {
  35472. var serializationObject = this.serialize();
  35473. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35474. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35475. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35476. serializationObject.positions._updatable = true;
  35477. }
  35478. }
  35479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35480. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35481. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35482. serializationObject.normals._updatable = true;
  35483. }
  35484. }
  35485. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35486. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35487. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35488. serializationObject.tangets._updatable = true;
  35489. }
  35490. }
  35491. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35492. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35493. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35494. serializationObject.uvs._updatable = true;
  35495. }
  35496. }
  35497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35498. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35499. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35500. serializationObject.uv2s._updatable = true;
  35501. }
  35502. }
  35503. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35504. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35505. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35506. serializationObject.uv3s._updatable = true;
  35507. }
  35508. }
  35509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35510. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35511. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35512. serializationObject.uv4s._updatable = true;
  35513. }
  35514. }
  35515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35516. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35517. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35518. serializationObject.uv5s._updatable = true;
  35519. }
  35520. }
  35521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35522. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35523. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35524. serializationObject.uv6s._updatable = true;
  35525. }
  35526. }
  35527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35528. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35529. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35530. serializationObject.colors._updatable = true;
  35531. }
  35532. }
  35533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35534. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35535. serializationObject.matricesIndices._isExpanded = true;
  35536. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35537. serializationObject.matricesIndices._updatable = true;
  35538. }
  35539. }
  35540. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35541. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35542. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35543. serializationObject.matricesWeights._updatable = true;
  35544. }
  35545. }
  35546. serializationObject.indices = this.toNumberArray(this.getIndices());
  35547. return serializationObject;
  35548. };
  35549. // Statics
  35550. /**
  35551. * Extracts a clone of a mesh geometry
  35552. * @param mesh defines the source mesh
  35553. * @param id defines the unique ID of the new geometry object
  35554. * @returns the new geometry object
  35555. */
  35556. Geometry.ExtractFromMesh = function (mesh, id) {
  35557. var geometry = mesh._geometry;
  35558. if (!geometry) {
  35559. return null;
  35560. }
  35561. return geometry.copy(id);
  35562. };
  35563. /**
  35564. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35565. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35566. * Be aware Math.random() could cause collisions, but:
  35567. * "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"
  35568. * @returns a string containing a new GUID
  35569. */
  35570. Geometry.RandomId = function () {
  35571. return BABYLON.Tools.RandomId();
  35572. };
  35573. /** @ignore */
  35574. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35575. var scene = mesh.getScene();
  35576. // Geometry
  35577. var geometryId = parsedGeometry.geometryId;
  35578. if (geometryId) {
  35579. var geometry = scene.getGeometryByID(geometryId);
  35580. if (geometry) {
  35581. geometry.applyToMesh(mesh);
  35582. }
  35583. }
  35584. else if (parsedGeometry instanceof ArrayBuffer) {
  35585. var binaryInfo = mesh._binaryInfo;
  35586. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35587. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35588. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35589. }
  35590. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35591. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35592. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35593. }
  35594. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35595. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35596. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35597. }
  35598. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35599. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35600. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35601. }
  35602. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35603. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35604. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35605. }
  35606. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35607. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35608. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35609. }
  35610. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35611. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35612. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35613. }
  35614. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35615. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35616. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35617. }
  35618. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35619. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35620. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35621. }
  35622. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35623. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35624. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35625. }
  35626. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35627. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35628. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35629. }
  35630. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35631. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35632. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35633. }
  35634. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35635. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35636. mesh.setIndices(indicesData, null);
  35637. }
  35638. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35639. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35640. mesh.subMeshes = [];
  35641. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35642. var materialIndex = subMeshesData[(i * 5) + 0];
  35643. var verticesStart = subMeshesData[(i * 5) + 1];
  35644. var verticesCount = subMeshesData[(i * 5) + 2];
  35645. var indexStart = subMeshesData[(i * 5) + 3];
  35646. var indexCount = subMeshesData[(i * 5) + 4];
  35647. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35648. }
  35649. }
  35650. }
  35651. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35652. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35653. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35654. if (parsedGeometry.tangents) {
  35655. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35656. }
  35657. if (parsedGeometry.uvs) {
  35658. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35659. }
  35660. if (parsedGeometry.uvs2) {
  35661. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35662. }
  35663. if (parsedGeometry.uvs3) {
  35664. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35665. }
  35666. if (parsedGeometry.uvs4) {
  35667. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35668. }
  35669. if (parsedGeometry.uvs5) {
  35670. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35671. }
  35672. if (parsedGeometry.uvs6) {
  35673. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35674. }
  35675. if (parsedGeometry.colors) {
  35676. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35677. }
  35678. if (parsedGeometry.matricesIndices) {
  35679. if (!parsedGeometry.matricesIndices._isExpanded) {
  35680. var floatIndices = [];
  35681. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35682. var matricesIndex = parsedGeometry.matricesIndices[i];
  35683. floatIndices.push(matricesIndex & 0x000000FF);
  35684. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35685. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35686. floatIndices.push(matricesIndex >> 24);
  35687. }
  35688. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35689. }
  35690. else {
  35691. delete parsedGeometry.matricesIndices._isExpanded;
  35692. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35693. }
  35694. }
  35695. if (parsedGeometry.matricesIndicesExtra) {
  35696. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35697. var floatIndices = [];
  35698. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35699. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35700. floatIndices.push(matricesIndex & 0x000000FF);
  35701. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35702. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35703. floatIndices.push(matricesIndex >> 24);
  35704. }
  35705. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35706. }
  35707. else {
  35708. delete parsedGeometry.matricesIndices._isExpanded;
  35709. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35710. }
  35711. }
  35712. if (parsedGeometry.matricesWeights) {
  35713. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35714. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35715. }
  35716. if (parsedGeometry.matricesWeightsExtra) {
  35717. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35718. }
  35719. mesh.setIndices(parsedGeometry.indices, null);
  35720. }
  35721. // SubMeshes
  35722. if (parsedGeometry.subMeshes) {
  35723. mesh.subMeshes = [];
  35724. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35725. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35726. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35727. }
  35728. }
  35729. // Flat shading
  35730. if (mesh._shouldGenerateFlatShading) {
  35731. mesh.convertToFlatShadedMesh();
  35732. delete mesh._shouldGenerateFlatShading;
  35733. }
  35734. // Update
  35735. mesh.computeWorldMatrix(true);
  35736. // Octree
  35737. var sceneOctree = scene.selectionOctree;
  35738. if (sceneOctree !== undefined && sceneOctree !== null) {
  35739. sceneOctree.addMesh(mesh);
  35740. }
  35741. };
  35742. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35743. var epsilon = 1e-3;
  35744. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35745. return;
  35746. }
  35747. var noInfluenceBoneIndex = 0.0;
  35748. if (parsedGeometry.skeletonId > -1) {
  35749. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35750. if (!skeleton) {
  35751. return;
  35752. }
  35753. noInfluenceBoneIndex = skeleton.bones.length;
  35754. }
  35755. else {
  35756. return;
  35757. }
  35758. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35759. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35760. var matricesWeights = parsedGeometry.matricesWeights;
  35761. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35762. var influencers = parsedGeometry.numBoneInfluencer;
  35763. var size = matricesWeights.length;
  35764. for (var i = 0; i < size; i += 4) {
  35765. var weight = 0.0;
  35766. var firstZeroWeight = -1;
  35767. for (var j = 0; j < 4; j++) {
  35768. var w = matricesWeights[i + j];
  35769. weight += w;
  35770. if (w < epsilon && firstZeroWeight < 0) {
  35771. firstZeroWeight = j;
  35772. }
  35773. }
  35774. if (matricesWeightsExtra) {
  35775. for (var j = 0; j < 4; j++) {
  35776. var w = matricesWeightsExtra[i + j];
  35777. weight += w;
  35778. if (w < epsilon && firstZeroWeight < 0) {
  35779. firstZeroWeight = j + 4;
  35780. }
  35781. }
  35782. }
  35783. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35784. firstZeroWeight = influencers - 1;
  35785. }
  35786. if (weight > epsilon) {
  35787. var mweight = 1.0 / weight;
  35788. for (var j = 0; j < 4; j++) {
  35789. matricesWeights[i + j] *= mweight;
  35790. }
  35791. if (matricesWeightsExtra) {
  35792. for (var j = 0; j < 4; j++) {
  35793. matricesWeightsExtra[i + j] *= mweight;
  35794. }
  35795. }
  35796. }
  35797. else {
  35798. if (firstZeroWeight >= 4) {
  35799. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35800. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35801. }
  35802. else {
  35803. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35804. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35805. }
  35806. }
  35807. }
  35808. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35809. if (parsedGeometry.matricesWeightsExtra) {
  35810. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35811. }
  35812. };
  35813. /**
  35814. * Create a new geometry from persisted data (Using .babylon file format)
  35815. * @param parsedVertexData defines the persisted data
  35816. * @param scene defines the hosting scene
  35817. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35818. * @returns the new geometry object
  35819. */
  35820. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35821. if (scene.getGeometryByID(parsedVertexData.id)) {
  35822. return null; // null since geometry could be something else than a box...
  35823. }
  35824. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35825. if (BABYLON.Tags) {
  35826. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35827. }
  35828. if (parsedVertexData.delayLoadingFile) {
  35829. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35830. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35831. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35832. geometry._delayInfo = [];
  35833. if (parsedVertexData.hasUVs) {
  35834. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35835. }
  35836. if (parsedVertexData.hasUVs2) {
  35837. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35838. }
  35839. if (parsedVertexData.hasUVs3) {
  35840. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35841. }
  35842. if (parsedVertexData.hasUVs4) {
  35843. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35844. }
  35845. if (parsedVertexData.hasUVs5) {
  35846. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35847. }
  35848. if (parsedVertexData.hasUVs6) {
  35849. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35850. }
  35851. if (parsedVertexData.hasColors) {
  35852. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35853. }
  35854. if (parsedVertexData.hasMatricesIndices) {
  35855. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35856. }
  35857. if (parsedVertexData.hasMatricesWeights) {
  35858. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35859. }
  35860. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35861. }
  35862. else {
  35863. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35864. }
  35865. scene.pushGeometry(geometry, true);
  35866. return geometry;
  35867. };
  35868. return Geometry;
  35869. }());
  35870. BABYLON.Geometry = Geometry;
  35871. // Primitives
  35872. /// Abstract class
  35873. /**
  35874. * Abstract class used to provide common services for all typed geometries
  35875. */
  35876. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35877. __extends(_PrimitiveGeometry, _super);
  35878. /**
  35879. * Creates a new typed geometry
  35880. * @param id defines the unique ID of the geometry
  35881. * @param scene defines the hosting scene
  35882. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35883. * @param mesh defines the hosting mesh (can be null)
  35884. */
  35885. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35886. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35887. if (mesh === void 0) { mesh = null; }
  35888. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35889. _this._canBeRegenerated = _canBeRegenerated;
  35890. _this._beingRegenerated = true;
  35891. _this.regenerate();
  35892. _this._beingRegenerated = false;
  35893. return _this;
  35894. }
  35895. /**
  35896. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35897. * @returns true if the geometry can be regenerated
  35898. */
  35899. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35900. return this._canBeRegenerated;
  35901. };
  35902. /**
  35903. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35904. */
  35905. _PrimitiveGeometry.prototype.regenerate = function () {
  35906. if (!this._canBeRegenerated) {
  35907. return;
  35908. }
  35909. this._beingRegenerated = true;
  35910. this.setAllVerticesData(this._regenerateVertexData(), false);
  35911. this._beingRegenerated = false;
  35912. };
  35913. /**
  35914. * Clone the geometry
  35915. * @param id defines the unique ID of the new geometry
  35916. * @returns the new geometry
  35917. */
  35918. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35919. return _super.prototype.copy.call(this, id);
  35920. };
  35921. // overrides
  35922. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35923. if (!this._beingRegenerated) {
  35924. return;
  35925. }
  35926. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35927. };
  35928. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35929. if (!this._beingRegenerated) {
  35930. return;
  35931. }
  35932. _super.prototype.setVerticesData.call(this, kind, data, false);
  35933. };
  35934. // to override
  35935. /** @ignore */
  35936. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35937. throw new Error("Abstract method");
  35938. };
  35939. _PrimitiveGeometry.prototype.copy = function (id) {
  35940. throw new Error("Must be overriden in sub-classes.");
  35941. };
  35942. _PrimitiveGeometry.prototype.serialize = function () {
  35943. var serializationObject = _super.prototype.serialize.call(this);
  35944. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35945. return serializationObject;
  35946. };
  35947. return _PrimitiveGeometry;
  35948. }(Geometry));
  35949. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35950. /**
  35951. * Creates a ribbon geometry
  35952. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35953. */
  35954. var RibbonGeometry = /** @class */ (function (_super) {
  35955. __extends(RibbonGeometry, _super);
  35956. /**
  35957. * Creates a ribbon geometry
  35958. * @param id defines the unique ID of the geometry
  35959. * @param scene defines the hosting scene
  35960. * @param pathArray defines the array of paths to use
  35961. * @param closeArray defines if the last path and the first path must be joined
  35962. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35963. * @param offset defines the offset between points
  35964. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35965. * @param mesh defines the hosting mesh (can be null)
  35966. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35967. */
  35968. function RibbonGeometry(id, scene,
  35969. /**
  35970. * Defines the array of paths to use
  35971. */
  35972. pathArray,
  35973. /**
  35974. * Defines if the last and first points of each path in your pathArray must be joined
  35975. */
  35976. closeArray,
  35977. /**
  35978. * Defines if the last and first points of each path in your pathArray must be joined
  35979. */
  35980. closePath,
  35981. /**
  35982. * Defines the offset between points
  35983. */
  35984. offset, canBeRegenerated, mesh,
  35985. /**
  35986. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35987. */
  35988. side) {
  35989. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35990. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35991. _this.pathArray = pathArray;
  35992. _this.closeArray = closeArray;
  35993. _this.closePath = closePath;
  35994. _this.offset = offset;
  35995. _this.side = side;
  35996. return _this;
  35997. }
  35998. /** @ignore */
  35999. RibbonGeometry.prototype._regenerateVertexData = function () {
  36000. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36001. };
  36002. RibbonGeometry.prototype.copy = function (id) {
  36003. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36004. };
  36005. return RibbonGeometry;
  36006. }(_PrimitiveGeometry));
  36007. BABYLON.RibbonGeometry = RibbonGeometry;
  36008. /**
  36009. * Creates a box geometry
  36010. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36011. */
  36012. var BoxGeometry = /** @class */ (function (_super) {
  36013. __extends(BoxGeometry, _super);
  36014. /**
  36015. * Creates a box geometry
  36016. * @param id defines the unique ID of the geometry
  36017. * @param scene defines the hosting scene
  36018. * @param size defines the zise of the box (width, height and depth are the same)
  36019. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36020. * @param mesh defines the hosting mesh (can be null)
  36021. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36022. */
  36023. function BoxGeometry(id, scene,
  36024. /**
  36025. * Defines the zise of the box (width, height and depth are the same)
  36026. */
  36027. size, canBeRegenerated, mesh,
  36028. /**
  36029. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36030. */
  36031. side) {
  36032. if (mesh === void 0) { mesh = null; }
  36033. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36034. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36035. _this.size = size;
  36036. _this.side = side;
  36037. return _this;
  36038. }
  36039. BoxGeometry.prototype._regenerateVertexData = function () {
  36040. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36041. };
  36042. BoxGeometry.prototype.copy = function (id) {
  36043. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36044. };
  36045. BoxGeometry.prototype.serialize = function () {
  36046. var serializationObject = _super.prototype.serialize.call(this);
  36047. serializationObject.size = this.size;
  36048. return serializationObject;
  36049. };
  36050. BoxGeometry.Parse = function (parsedBox, scene) {
  36051. if (scene.getGeometryByID(parsedBox.id)) {
  36052. return null; // null since geometry could be something else than a box...
  36053. }
  36054. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36055. if (BABYLON.Tags) {
  36056. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36057. }
  36058. scene.pushGeometry(box, true);
  36059. return box;
  36060. };
  36061. return BoxGeometry;
  36062. }(_PrimitiveGeometry));
  36063. BABYLON.BoxGeometry = BoxGeometry;
  36064. /**
  36065. * Creates a sphere geometry
  36066. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36067. */
  36068. var SphereGeometry = /** @class */ (function (_super) {
  36069. __extends(SphereGeometry, _super);
  36070. /**
  36071. * Create a new sphere geometry
  36072. * @param id defines the unique ID of the geometry
  36073. * @param scene defines the hosting scene
  36074. * @param segments defines the number of segments to use to create the sphere
  36075. * @param diameter defines the diameter of the sphere
  36076. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36077. * @param mesh defines the hosting mesh (can be null)
  36078. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36079. */
  36080. function SphereGeometry(id, scene,
  36081. /**
  36082. * Defines the number of segments to use to create the sphere
  36083. */
  36084. segments,
  36085. /**
  36086. * Defines the diameter of the sphere
  36087. */
  36088. diameter, canBeRegenerated, mesh,
  36089. /**
  36090. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36091. */
  36092. side) {
  36093. if (mesh === void 0) { mesh = null; }
  36094. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36095. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36096. _this.segments = segments;
  36097. _this.diameter = diameter;
  36098. _this.side = side;
  36099. return _this;
  36100. }
  36101. SphereGeometry.prototype._regenerateVertexData = function () {
  36102. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36103. };
  36104. SphereGeometry.prototype.copy = function (id) {
  36105. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36106. };
  36107. SphereGeometry.prototype.serialize = function () {
  36108. var serializationObject = _super.prototype.serialize.call(this);
  36109. serializationObject.segments = this.segments;
  36110. serializationObject.diameter = this.diameter;
  36111. return serializationObject;
  36112. };
  36113. SphereGeometry.Parse = function (parsedSphere, scene) {
  36114. if (scene.getGeometryByID(parsedSphere.id)) {
  36115. return null; // null since geometry could be something else than a sphere...
  36116. }
  36117. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36118. if (BABYLON.Tags) {
  36119. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36120. }
  36121. scene.pushGeometry(sphere, true);
  36122. return sphere;
  36123. };
  36124. return SphereGeometry;
  36125. }(_PrimitiveGeometry));
  36126. BABYLON.SphereGeometry = SphereGeometry;
  36127. /**
  36128. * Creates a disc geometry
  36129. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36130. */
  36131. var DiscGeometry = /** @class */ (function (_super) {
  36132. __extends(DiscGeometry, _super);
  36133. /**
  36134. * Creates a new disc geometry
  36135. * @param id defines the unique ID of the geometry
  36136. * @param scene defines the hosting scene
  36137. * @param radius defines the radius of the disc
  36138. * @param tessellation defines the tesselation factor to apply to the disc
  36139. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36140. * @param mesh defines the hosting mesh (can be null)
  36141. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36142. */
  36143. function DiscGeometry(id, scene,
  36144. /**
  36145. * Defines the radius of the disc
  36146. */
  36147. radius,
  36148. /**
  36149. * Defines the tesselation factor to apply to the disc
  36150. */
  36151. tessellation, canBeRegenerated, mesh,
  36152. /**
  36153. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36154. */
  36155. side) {
  36156. if (mesh === void 0) { mesh = null; }
  36157. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36158. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36159. _this.radius = radius;
  36160. _this.tessellation = tessellation;
  36161. _this.side = side;
  36162. return _this;
  36163. }
  36164. DiscGeometry.prototype._regenerateVertexData = function () {
  36165. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36166. };
  36167. DiscGeometry.prototype.copy = function (id) {
  36168. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36169. };
  36170. return DiscGeometry;
  36171. }(_PrimitiveGeometry));
  36172. BABYLON.DiscGeometry = DiscGeometry;
  36173. /**
  36174. * Creates a new cylinder geometry
  36175. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36176. */
  36177. var CylinderGeometry = /** @class */ (function (_super) {
  36178. __extends(CylinderGeometry, _super);
  36179. /**
  36180. * Creates a new cylinder geometry
  36181. * @param id defines the unique ID of the geometry
  36182. * @param scene defines the hosting scene
  36183. * @param height defines the height of the cylinder
  36184. * @param diameterTop defines the diameter of the cylinder's top cap
  36185. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36186. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36187. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36188. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36189. * @param mesh defines the hosting mesh (can be null)
  36190. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36191. */
  36192. function CylinderGeometry(id, scene,
  36193. /**
  36194. * Defines the height of the cylinder
  36195. */
  36196. height,
  36197. /**
  36198. * Defines the diameter of the cylinder's top cap
  36199. */
  36200. diameterTop,
  36201. /**
  36202. * Defines the diameter of the cylinder's bottom cap
  36203. */
  36204. diameterBottom,
  36205. /**
  36206. * Defines the tessellation factor to apply to the cylinder
  36207. */
  36208. tessellation,
  36209. /**
  36210. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36211. */
  36212. subdivisions, canBeRegenerated, mesh,
  36213. /**
  36214. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36215. */
  36216. side) {
  36217. if (subdivisions === void 0) { subdivisions = 1; }
  36218. if (mesh === void 0) { mesh = null; }
  36219. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36220. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36221. _this.height = height;
  36222. _this.diameterTop = diameterTop;
  36223. _this.diameterBottom = diameterBottom;
  36224. _this.tessellation = tessellation;
  36225. _this.subdivisions = subdivisions;
  36226. _this.side = side;
  36227. return _this;
  36228. }
  36229. CylinderGeometry.prototype._regenerateVertexData = function () {
  36230. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36231. };
  36232. CylinderGeometry.prototype.copy = function (id) {
  36233. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36234. };
  36235. CylinderGeometry.prototype.serialize = function () {
  36236. var serializationObject = _super.prototype.serialize.call(this);
  36237. serializationObject.height = this.height;
  36238. serializationObject.diameterTop = this.diameterTop;
  36239. serializationObject.diameterBottom = this.diameterBottom;
  36240. serializationObject.tessellation = this.tessellation;
  36241. return serializationObject;
  36242. };
  36243. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36244. if (scene.getGeometryByID(parsedCylinder.id)) {
  36245. return null; // null since geometry could be something else than a cylinder...
  36246. }
  36247. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36248. if (BABYLON.Tags) {
  36249. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36250. }
  36251. scene.pushGeometry(cylinder, true);
  36252. return cylinder;
  36253. };
  36254. return CylinderGeometry;
  36255. }(_PrimitiveGeometry));
  36256. BABYLON.CylinderGeometry = CylinderGeometry;
  36257. /**
  36258. * Creates a new torus geometry
  36259. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36260. */
  36261. var TorusGeometry = /** @class */ (function (_super) {
  36262. __extends(TorusGeometry, _super);
  36263. /**
  36264. * Creates a new torus geometry
  36265. * @param id defines the unique ID of the geometry
  36266. * @param scene defines the hosting scene
  36267. * @param diameter defines the diameter of the torus
  36268. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36269. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36270. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36271. * @param mesh defines the hosting mesh (can be null)
  36272. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36273. */
  36274. function TorusGeometry(id, scene,
  36275. /**
  36276. * Defines the diameter of the torus
  36277. */
  36278. diameter,
  36279. /**
  36280. * Defines the thickness of the torus (ie. internal diameter)
  36281. */
  36282. thickness,
  36283. /**
  36284. * Defines the tesselation factor to apply to the torus
  36285. */
  36286. tessellation, canBeRegenerated, mesh,
  36287. /**
  36288. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36289. */
  36290. side) {
  36291. if (mesh === void 0) { mesh = null; }
  36292. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36293. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36294. _this.diameter = diameter;
  36295. _this.thickness = thickness;
  36296. _this.tessellation = tessellation;
  36297. _this.side = side;
  36298. return _this;
  36299. }
  36300. TorusGeometry.prototype._regenerateVertexData = function () {
  36301. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36302. };
  36303. TorusGeometry.prototype.copy = function (id) {
  36304. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36305. };
  36306. TorusGeometry.prototype.serialize = function () {
  36307. var serializationObject = _super.prototype.serialize.call(this);
  36308. serializationObject.diameter = this.diameter;
  36309. serializationObject.thickness = this.thickness;
  36310. serializationObject.tessellation = this.tessellation;
  36311. return serializationObject;
  36312. };
  36313. TorusGeometry.Parse = function (parsedTorus, scene) {
  36314. if (scene.getGeometryByID(parsedTorus.id)) {
  36315. return null; // null since geometry could be something else than a torus...
  36316. }
  36317. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36318. if (BABYLON.Tags) {
  36319. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36320. }
  36321. scene.pushGeometry(torus, true);
  36322. return torus;
  36323. };
  36324. return TorusGeometry;
  36325. }(_PrimitiveGeometry));
  36326. BABYLON.TorusGeometry = TorusGeometry;
  36327. /**
  36328. * Creates a new ground geometry
  36329. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36330. */
  36331. var GroundGeometry = /** @class */ (function (_super) {
  36332. __extends(GroundGeometry, _super);
  36333. /**
  36334. * Creates a new ground geometry
  36335. * @param id defines the unique ID of the geometry
  36336. * @param scene defines the hosting scene
  36337. * @param width defines the width of the ground
  36338. * @param height defines the height of the ground
  36339. * @param subdivisions defines the subdivisions to apply to the ground
  36340. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36341. * @param mesh defines the hosting mesh (can be null)
  36342. */
  36343. function GroundGeometry(id, scene,
  36344. /**
  36345. * Defines the width of the ground
  36346. */
  36347. width,
  36348. /**
  36349. * Defines the height of the ground
  36350. */
  36351. height,
  36352. /**
  36353. * Defines the subdivisions to apply to the ground
  36354. */
  36355. subdivisions, canBeRegenerated, mesh) {
  36356. if (mesh === void 0) { mesh = null; }
  36357. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36358. _this.width = width;
  36359. _this.height = height;
  36360. _this.subdivisions = subdivisions;
  36361. return _this;
  36362. }
  36363. GroundGeometry.prototype._regenerateVertexData = function () {
  36364. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36365. };
  36366. GroundGeometry.prototype.copy = function (id) {
  36367. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36368. };
  36369. GroundGeometry.prototype.serialize = function () {
  36370. var serializationObject = _super.prototype.serialize.call(this);
  36371. serializationObject.width = this.width;
  36372. serializationObject.height = this.height;
  36373. serializationObject.subdivisions = this.subdivisions;
  36374. return serializationObject;
  36375. };
  36376. GroundGeometry.Parse = function (parsedGround, scene) {
  36377. if (scene.getGeometryByID(parsedGround.id)) {
  36378. return null; // null since geometry could be something else than a ground...
  36379. }
  36380. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36381. if (BABYLON.Tags) {
  36382. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36383. }
  36384. scene.pushGeometry(ground, true);
  36385. return ground;
  36386. };
  36387. return GroundGeometry;
  36388. }(_PrimitiveGeometry));
  36389. BABYLON.GroundGeometry = GroundGeometry;
  36390. /**
  36391. * Creates a tiled ground geometry
  36392. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36393. */
  36394. var TiledGroundGeometry = /** @class */ (function (_super) {
  36395. __extends(TiledGroundGeometry, _super);
  36396. /**
  36397. * Creates a tiled ground geometry
  36398. * @param id defines the unique ID of the geometry
  36399. * @param scene defines the hosting scene
  36400. * @param xmin defines the minimum value on X axis
  36401. * @param zmin defines the minimum value on Z axis
  36402. * @param xmax defines the maximum value on X axis
  36403. * @param zmax defines the maximum value on Z axis
  36404. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36405. * @param precision defines the precision to use when computing the tiles
  36406. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36407. * @param mesh defines the hosting mesh (can be null)
  36408. */
  36409. function TiledGroundGeometry(id, scene,
  36410. /**
  36411. * Defines the minimum value on X axis
  36412. */
  36413. xmin,
  36414. /**
  36415. * Defines the minimum value on Z axis
  36416. */
  36417. zmin,
  36418. /**
  36419. * Defines the maximum value on X axis
  36420. */
  36421. xmax,
  36422. /**
  36423. * Defines the maximum value on Z axis
  36424. */
  36425. zmax,
  36426. /**
  36427. * Defines the subdivisions to apply to the ground
  36428. */
  36429. subdivisions,
  36430. /**
  36431. * Defines the precision to use when computing the tiles
  36432. */
  36433. precision, canBeRegenerated, mesh) {
  36434. if (mesh === void 0) { mesh = null; }
  36435. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36436. _this.xmin = xmin;
  36437. _this.zmin = zmin;
  36438. _this.xmax = xmax;
  36439. _this.zmax = zmax;
  36440. _this.subdivisions = subdivisions;
  36441. _this.precision = precision;
  36442. return _this;
  36443. }
  36444. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36445. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36446. };
  36447. TiledGroundGeometry.prototype.copy = function (id) {
  36448. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36449. };
  36450. return TiledGroundGeometry;
  36451. }(_PrimitiveGeometry));
  36452. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36453. /**
  36454. * Creates a plane geometry
  36455. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36456. */
  36457. var PlaneGeometry = /** @class */ (function (_super) {
  36458. __extends(PlaneGeometry, _super);
  36459. /**
  36460. * Creates a plane geometry
  36461. * @param id defines the unique ID of the geometry
  36462. * @param scene defines the hosting scene
  36463. * @param size defines the size of the plane (width === height)
  36464. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36465. * @param mesh defines the hosting mesh (can be null)
  36466. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36467. */
  36468. function PlaneGeometry(id, scene,
  36469. /**
  36470. * Defines the size of the plane (width === height)
  36471. */
  36472. size, canBeRegenerated, mesh,
  36473. /**
  36474. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36475. */
  36476. side) {
  36477. if (mesh === void 0) { mesh = null; }
  36478. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36479. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36480. _this.size = size;
  36481. _this.side = side;
  36482. return _this;
  36483. }
  36484. PlaneGeometry.prototype._regenerateVertexData = function () {
  36485. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36486. };
  36487. PlaneGeometry.prototype.copy = function (id) {
  36488. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36489. };
  36490. PlaneGeometry.prototype.serialize = function () {
  36491. var serializationObject = _super.prototype.serialize.call(this);
  36492. serializationObject.size = this.size;
  36493. return serializationObject;
  36494. };
  36495. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36496. if (scene.getGeometryByID(parsedPlane.id)) {
  36497. return null; // null since geometry could be something else than a ground...
  36498. }
  36499. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36500. if (BABYLON.Tags) {
  36501. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36502. }
  36503. scene.pushGeometry(plane, true);
  36504. return plane;
  36505. };
  36506. return PlaneGeometry;
  36507. }(_PrimitiveGeometry));
  36508. BABYLON.PlaneGeometry = PlaneGeometry;
  36509. /**
  36510. * Creates a torus knot geometry
  36511. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36512. */
  36513. var TorusKnotGeometry = /** @class */ (function (_super) {
  36514. __extends(TorusKnotGeometry, _super);
  36515. /**
  36516. * Creates a torus knot geometry
  36517. * @param id defines the unique ID of the geometry
  36518. * @param scene defines the hosting scene
  36519. * @param radius defines the radius of the torus knot
  36520. * @param tube defines the thickness of the torus knot tube
  36521. * @param radialSegments defines the number of radial segments
  36522. * @param tubularSegments defines the number of tubular segments
  36523. * @param p defines the first number of windings
  36524. * @param q defines the second number of windings
  36525. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36526. * @param mesh defines the hosting mesh (can be null)
  36527. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36528. */
  36529. function TorusKnotGeometry(id, scene,
  36530. /**
  36531. * Defines the radius of the torus knot
  36532. */
  36533. radius,
  36534. /**
  36535. * Defines the thickness of the torus knot tube
  36536. */
  36537. tube,
  36538. /**
  36539. * Defines the number of radial segments
  36540. */
  36541. radialSegments,
  36542. /**
  36543. * Defines the number of tubular segments
  36544. */
  36545. tubularSegments,
  36546. /**
  36547. * Defines the first number of windings
  36548. */
  36549. p,
  36550. /**
  36551. * Defines the second number of windings
  36552. */
  36553. q, canBeRegenerated, mesh,
  36554. /**
  36555. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36556. */
  36557. side) {
  36558. if (mesh === void 0) { mesh = null; }
  36559. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36560. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36561. _this.radius = radius;
  36562. _this.tube = tube;
  36563. _this.radialSegments = radialSegments;
  36564. _this.tubularSegments = tubularSegments;
  36565. _this.p = p;
  36566. _this.q = q;
  36567. _this.side = side;
  36568. return _this;
  36569. }
  36570. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36571. 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 });
  36572. };
  36573. TorusKnotGeometry.prototype.copy = function (id) {
  36574. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36575. };
  36576. TorusKnotGeometry.prototype.serialize = function () {
  36577. var serializationObject = _super.prototype.serialize.call(this);
  36578. serializationObject.radius = this.radius;
  36579. serializationObject.tube = this.tube;
  36580. serializationObject.radialSegments = this.radialSegments;
  36581. serializationObject.tubularSegments = this.tubularSegments;
  36582. serializationObject.p = this.p;
  36583. serializationObject.q = this.q;
  36584. return serializationObject;
  36585. };
  36586. ;
  36587. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36588. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36589. return null; // null since geometry could be something else than a ground...
  36590. }
  36591. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36592. if (BABYLON.Tags) {
  36593. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36594. }
  36595. scene.pushGeometry(torusKnot, true);
  36596. return torusKnot;
  36597. };
  36598. return TorusKnotGeometry;
  36599. }(_PrimitiveGeometry));
  36600. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36601. //}
  36602. })(BABYLON || (BABYLON = {}));
  36603. //# sourceMappingURL=babylon.geometry.js.map
  36604. var BABYLON;
  36605. (function (BABYLON) {
  36606. /**
  36607. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36608. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36609. */
  36610. var PostProcessManager = /** @class */ (function () {
  36611. /**
  36612. * Creates a new instance of @see PostProcess
  36613. * @param scene The scene that the post process is associated with.
  36614. */
  36615. function PostProcessManager(scene) {
  36616. this._vertexBuffers = {};
  36617. this._scene = scene;
  36618. }
  36619. PostProcessManager.prototype._prepareBuffers = function () {
  36620. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36621. return;
  36622. }
  36623. // VBO
  36624. var vertices = [];
  36625. vertices.push(1, 1);
  36626. vertices.push(-1, 1);
  36627. vertices.push(-1, -1);
  36628. vertices.push(1, -1);
  36629. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36630. this._buildIndexBuffer();
  36631. };
  36632. PostProcessManager.prototype._buildIndexBuffer = function () {
  36633. // Indices
  36634. var indices = [];
  36635. indices.push(0);
  36636. indices.push(1);
  36637. indices.push(2);
  36638. indices.push(0);
  36639. indices.push(2);
  36640. indices.push(3);
  36641. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36642. };
  36643. /**
  36644. * Rebuilds the vertex buffers of the manager.
  36645. */
  36646. PostProcessManager.prototype._rebuild = function () {
  36647. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36648. if (!vb) {
  36649. return;
  36650. }
  36651. vb._rebuild();
  36652. this._buildIndexBuffer();
  36653. };
  36654. // Methods
  36655. /**
  36656. * Prepares a frame to be run through a post process.
  36657. * @param sourceTexture The input texture to the post procesess. (default: null)
  36658. * @param postProcesses An array of post processes to be run. (default: null)
  36659. * @returns True if the post processes were able to be run.
  36660. */
  36661. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36662. if (sourceTexture === void 0) { sourceTexture = null; }
  36663. if (postProcesses === void 0) { postProcesses = null; }
  36664. var camera = this._scene.activeCamera;
  36665. if (!camera) {
  36666. return false;
  36667. }
  36668. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36669. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36670. return false;
  36671. }
  36672. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36673. return true;
  36674. };
  36675. /**
  36676. * Manually render a set of post processes to a texture.
  36677. * @param postProcesses An array of post processes to be run.
  36678. * @param targetTexture The target texture to render to.
  36679. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36680. */
  36681. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36682. if (targetTexture === void 0) { targetTexture = null; }
  36683. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36684. var engine = this._scene.getEngine();
  36685. for (var index = 0; index < postProcesses.length; index++) {
  36686. if (index < postProcesses.length - 1) {
  36687. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36688. }
  36689. else {
  36690. if (targetTexture) {
  36691. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36692. }
  36693. else {
  36694. engine.restoreDefaultFramebuffer();
  36695. }
  36696. }
  36697. var pp = postProcesses[index];
  36698. var effect = pp.apply();
  36699. if (effect) {
  36700. pp.onBeforeRenderObservable.notifyObservers(effect);
  36701. // VBOs
  36702. this._prepareBuffers();
  36703. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36704. // Draw order
  36705. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36706. pp.onAfterRenderObservable.notifyObservers(effect);
  36707. }
  36708. }
  36709. // Restore depth buffer
  36710. engine.setDepthBuffer(true);
  36711. engine.setDepthWrite(true);
  36712. };
  36713. /**
  36714. * Finalize the result of the output of the postprocesses.
  36715. * @param doNotPresent If true the result will not be displayed to the screen.
  36716. * @param targetTexture The target texture to render to.
  36717. * @param faceIndex The index of the face to bind the target texture to.
  36718. * @param postProcesses The array of post processes to render.
  36719. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36720. */
  36721. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36722. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36723. var camera = this._scene.activeCamera;
  36724. if (!camera) {
  36725. return;
  36726. }
  36727. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36728. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36729. return;
  36730. }
  36731. var engine = this._scene.getEngine();
  36732. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36733. if (index < len - 1) {
  36734. postProcesses[index + 1].activate(camera, targetTexture);
  36735. }
  36736. else {
  36737. if (targetTexture) {
  36738. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36739. }
  36740. else {
  36741. engine.restoreDefaultFramebuffer();
  36742. }
  36743. }
  36744. if (doNotPresent) {
  36745. break;
  36746. }
  36747. var pp = postProcesses[index];
  36748. var effect = pp.apply();
  36749. if (effect) {
  36750. pp.onBeforeRenderObservable.notifyObservers(effect);
  36751. // VBOs
  36752. this._prepareBuffers();
  36753. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36754. // Draw order
  36755. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36756. pp.onAfterRenderObservable.notifyObservers(effect);
  36757. }
  36758. }
  36759. // Restore states
  36760. engine.setDepthBuffer(true);
  36761. engine.setDepthWrite(true);
  36762. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36763. };
  36764. /**
  36765. * Disposes of the post process manager.
  36766. */
  36767. PostProcessManager.prototype.dispose = function () {
  36768. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36769. if (buffer) {
  36770. buffer.dispose();
  36771. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36772. }
  36773. if (this._indexBuffer) {
  36774. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36775. this._indexBuffer = null;
  36776. }
  36777. };
  36778. return PostProcessManager;
  36779. }());
  36780. BABYLON.PostProcessManager = PostProcessManager;
  36781. })(BABYLON || (BABYLON = {}));
  36782. //# sourceMappingURL=babylon.postProcessManager.js.map
  36783. var BABYLON;
  36784. (function (BABYLON) {
  36785. /**
  36786. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36787. */
  36788. var PerformanceMonitor = /** @class */ (function () {
  36789. /**
  36790. * constructor
  36791. * @param frameSampleSize The number of samples required to saturate the sliding window
  36792. */
  36793. function PerformanceMonitor(frameSampleSize) {
  36794. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36795. this._enabled = true;
  36796. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36797. }
  36798. /**
  36799. * Samples current frame
  36800. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36801. */
  36802. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36803. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36804. if (!this._enabled)
  36805. return;
  36806. if (this._lastFrameTimeMs != null) {
  36807. var dt = timeMs - this._lastFrameTimeMs;
  36808. this._rollingFrameTime.add(dt);
  36809. }
  36810. this._lastFrameTimeMs = timeMs;
  36811. };
  36812. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36813. /**
  36814. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36815. * @return Average frame time in milliseconds
  36816. */
  36817. get: function () {
  36818. return this._rollingFrameTime.average;
  36819. },
  36820. enumerable: true,
  36821. configurable: true
  36822. });
  36823. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36824. /**
  36825. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36826. * @return Frame time variance in milliseconds squared
  36827. */
  36828. get: function () {
  36829. return this._rollingFrameTime.variance;
  36830. },
  36831. enumerable: true,
  36832. configurable: true
  36833. });
  36834. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36835. /**
  36836. * Returns the frame time of the most recent frame
  36837. * @return Frame time in milliseconds
  36838. */
  36839. get: function () {
  36840. return this._rollingFrameTime.history(0);
  36841. },
  36842. enumerable: true,
  36843. configurable: true
  36844. });
  36845. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36846. /**
  36847. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36848. * @return Framerate in frames per second
  36849. */
  36850. get: function () {
  36851. return 1000.0 / this._rollingFrameTime.average;
  36852. },
  36853. enumerable: true,
  36854. configurable: true
  36855. });
  36856. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36857. /**
  36858. * Returns the average framerate in frames per second using the most recent frame time
  36859. * @return Framerate in frames per second
  36860. */
  36861. get: function () {
  36862. var history = this._rollingFrameTime.history(0);
  36863. if (history === 0) {
  36864. return 0;
  36865. }
  36866. return 1000.0 / history;
  36867. },
  36868. enumerable: true,
  36869. configurable: true
  36870. });
  36871. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36872. /**
  36873. * Returns true if enough samples have been taken to completely fill the sliding window
  36874. * @return true if saturated
  36875. */
  36876. get: function () {
  36877. return this._rollingFrameTime.isSaturated();
  36878. },
  36879. enumerable: true,
  36880. configurable: true
  36881. });
  36882. /**
  36883. * Enables contributions to the sliding window sample set
  36884. */
  36885. PerformanceMonitor.prototype.enable = function () {
  36886. this._enabled = true;
  36887. };
  36888. /**
  36889. * Disables contributions to the sliding window sample set
  36890. * Samples will not be interpolated over the disabled period
  36891. */
  36892. PerformanceMonitor.prototype.disable = function () {
  36893. this._enabled = false;
  36894. //clear last sample to avoid interpolating over the disabled period when next enabled
  36895. this._lastFrameTimeMs = null;
  36896. };
  36897. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36898. /**
  36899. * Returns true if sampling is enabled
  36900. * @return true if enabled
  36901. */
  36902. get: function () {
  36903. return this._enabled;
  36904. },
  36905. enumerable: true,
  36906. configurable: true
  36907. });
  36908. /**
  36909. * Resets performance monitor
  36910. */
  36911. PerformanceMonitor.prototype.reset = function () {
  36912. //clear last sample to avoid interpolating over the disabled period when next enabled
  36913. this._lastFrameTimeMs = null;
  36914. //wipe record
  36915. this._rollingFrameTime.reset();
  36916. };
  36917. return PerformanceMonitor;
  36918. }());
  36919. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36920. /**
  36921. * RollingAverage
  36922. *
  36923. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36924. */
  36925. var RollingAverage = /** @class */ (function () {
  36926. /**
  36927. * constructor
  36928. * @param length The number of samples required to saturate the sliding window
  36929. */
  36930. function RollingAverage(length) {
  36931. this._samples = new Array(length);
  36932. this.reset();
  36933. }
  36934. /**
  36935. * Adds a sample to the sample set
  36936. * @param v The sample value
  36937. */
  36938. RollingAverage.prototype.add = function (v) {
  36939. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36940. var delta;
  36941. //we need to check if we've already wrapped round
  36942. if (this.isSaturated()) {
  36943. //remove bottom of stack from mean
  36944. var bottomValue = this._samples[this._pos];
  36945. delta = bottomValue - this.average;
  36946. this.average -= delta / (this._sampleCount - 1);
  36947. this._m2 -= delta * (bottomValue - this.average);
  36948. }
  36949. else {
  36950. this._sampleCount++;
  36951. }
  36952. //add new value to mean
  36953. delta = v - this.average;
  36954. this.average += delta / (this._sampleCount);
  36955. this._m2 += delta * (v - this.average);
  36956. //set the new variance
  36957. this.variance = this._m2 / (this._sampleCount - 1);
  36958. this._samples[this._pos] = v;
  36959. this._pos++;
  36960. this._pos %= this._samples.length; //positive wrap around
  36961. };
  36962. /**
  36963. * Returns previously added values or null if outside of history or outside the sliding window domain
  36964. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36965. * @return Value previously recorded with add() or null if outside of range
  36966. */
  36967. RollingAverage.prototype.history = function (i) {
  36968. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36969. return 0;
  36970. }
  36971. var i0 = this._wrapPosition(this._pos - 1.0);
  36972. return this._samples[this._wrapPosition(i0 - i)];
  36973. };
  36974. /**
  36975. * Returns true if enough samples have been taken to completely fill the sliding window
  36976. * @return true if sample-set saturated
  36977. */
  36978. RollingAverage.prototype.isSaturated = function () {
  36979. return this._sampleCount >= this._samples.length;
  36980. };
  36981. /**
  36982. * Resets the rolling average (equivalent to 0 samples taken so far)
  36983. */
  36984. RollingAverage.prototype.reset = function () {
  36985. this.average = 0;
  36986. this.variance = 0;
  36987. this._sampleCount = 0;
  36988. this._pos = 0;
  36989. this._m2 = 0;
  36990. };
  36991. /**
  36992. * Wraps a value around the sample range boundaries
  36993. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36994. * @return Wrapped position in sample range
  36995. */
  36996. RollingAverage.prototype._wrapPosition = function (i) {
  36997. var max = this._samples.length;
  36998. return ((i % max) + max) % max;
  36999. };
  37000. return RollingAverage;
  37001. }());
  37002. BABYLON.RollingAverage = RollingAverage;
  37003. })(BABYLON || (BABYLON = {}));
  37004. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37005. var BABYLON;
  37006. (function (BABYLON) {
  37007. /**
  37008. * This groups together the common properties used for image processing either in direct forward pass
  37009. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37010. * or not.
  37011. */
  37012. var ImageProcessingConfiguration = /** @class */ (function () {
  37013. function ImageProcessingConfiguration() {
  37014. /**
  37015. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37016. */
  37017. this.colorCurves = new BABYLON.ColorCurves();
  37018. this._colorCurvesEnabled = false;
  37019. this._colorGradingEnabled = false;
  37020. this._colorGradingWithGreenDepth = true;
  37021. this._colorGradingBGR = true;
  37022. this._exposure = 1.0;
  37023. this._toneMappingEnabled = false;
  37024. this._contrast = 1.0;
  37025. /**
  37026. * Vignette stretch size.
  37027. */
  37028. this.vignetteStretch = 0;
  37029. /**
  37030. * Vignette centre X Offset.
  37031. */
  37032. this.vignetteCentreX = 0;
  37033. /**
  37034. * Vignette centre Y Offset.
  37035. */
  37036. this.vignetteCentreY = 0;
  37037. /**
  37038. * Vignette weight or intensity of the vignette effect.
  37039. */
  37040. this.vignetteWeight = 1.5;
  37041. /**
  37042. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37043. * if vignetteEnabled is set to true.
  37044. */
  37045. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37046. /**
  37047. * Camera field of view used by the Vignette effect.
  37048. */
  37049. this.vignetteCameraFov = 0.5;
  37050. this._grainEnabled = false;
  37051. this._grainIntensity = 30;
  37052. this._grainAnimated = false;
  37053. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37054. this._vignetteEnabled = false;
  37055. this._applyByPostProcess = false;
  37056. this._isEnabled = true;
  37057. /**
  37058. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37059. * @type {BABYLON.Observable}
  37060. */
  37061. this.onUpdateParameters = new BABYLON.Observable();
  37062. }
  37063. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37064. /**
  37065. * Gets wether the color curves effect is enabled.
  37066. */
  37067. get: function () {
  37068. return this._colorCurvesEnabled;
  37069. },
  37070. /**
  37071. * Sets wether the color curves effect is enabled.
  37072. */
  37073. set: function (value) {
  37074. if (this._colorCurvesEnabled === value) {
  37075. return;
  37076. }
  37077. this._colorCurvesEnabled = value;
  37078. this._updateParameters();
  37079. },
  37080. enumerable: true,
  37081. configurable: true
  37082. });
  37083. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37084. /**
  37085. * Gets wether the color grading effect is enabled.
  37086. */
  37087. get: function () {
  37088. return this._colorGradingEnabled;
  37089. },
  37090. /**
  37091. * Sets wether the color grading effect is enabled.
  37092. */
  37093. set: function (value) {
  37094. if (this._colorGradingEnabled === value) {
  37095. return;
  37096. }
  37097. this._colorGradingEnabled = value;
  37098. this._updateParameters();
  37099. },
  37100. enumerable: true,
  37101. configurable: true
  37102. });
  37103. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37104. /**
  37105. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37106. */
  37107. get: function () {
  37108. return this._colorGradingWithGreenDepth;
  37109. },
  37110. /**
  37111. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37112. */
  37113. set: function (value) {
  37114. if (this._colorGradingWithGreenDepth === value) {
  37115. return;
  37116. }
  37117. this._colorGradingWithGreenDepth = value;
  37118. this._updateParameters();
  37119. },
  37120. enumerable: true,
  37121. configurable: true
  37122. });
  37123. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37124. /**
  37125. * Gets wether the color grading texture contains BGR values.
  37126. */
  37127. get: function () {
  37128. return this._colorGradingBGR;
  37129. },
  37130. /**
  37131. * Sets wether the color grading texture contains BGR values.
  37132. */
  37133. set: function (value) {
  37134. if (this._colorGradingBGR === value) {
  37135. return;
  37136. }
  37137. this._colorGradingBGR = value;
  37138. this._updateParameters();
  37139. },
  37140. enumerable: true,
  37141. configurable: true
  37142. });
  37143. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37144. /**
  37145. * Gets the Exposure used in the effect.
  37146. */
  37147. get: function () {
  37148. return this._exposure;
  37149. },
  37150. /**
  37151. * Sets the Exposure used in the effect.
  37152. */
  37153. set: function (value) {
  37154. if (this._exposure === value) {
  37155. return;
  37156. }
  37157. this._exposure = value;
  37158. this._updateParameters();
  37159. },
  37160. enumerable: true,
  37161. configurable: true
  37162. });
  37163. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37164. /**
  37165. * Gets wether the tone mapping effect is enabled.
  37166. */
  37167. get: function () {
  37168. return this._toneMappingEnabled;
  37169. },
  37170. /**
  37171. * Sets wether the tone mapping effect is enabled.
  37172. */
  37173. set: function (value) {
  37174. if (this._toneMappingEnabled === value) {
  37175. return;
  37176. }
  37177. this._toneMappingEnabled = value;
  37178. this._updateParameters();
  37179. },
  37180. enumerable: true,
  37181. configurable: true
  37182. });
  37183. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37184. /**
  37185. * Gets the contrast used in the effect.
  37186. */
  37187. get: function () {
  37188. return this._contrast;
  37189. },
  37190. /**
  37191. * Sets the contrast used in the effect.
  37192. */
  37193. set: function (value) {
  37194. if (this._contrast === value) {
  37195. return;
  37196. }
  37197. this._contrast = value;
  37198. this._updateParameters();
  37199. },
  37200. enumerable: true,
  37201. configurable: true
  37202. });
  37203. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37204. /**
  37205. * If the grain effect should be enabled.
  37206. */
  37207. get: function () {
  37208. return this._grainEnabled;
  37209. },
  37210. set: function (value) {
  37211. if (this._grainEnabled === value) {
  37212. return;
  37213. }
  37214. this._grainEnabled = value;
  37215. this._updateParameters();
  37216. },
  37217. enumerable: true,
  37218. configurable: true
  37219. });
  37220. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37221. /**
  37222. * Amount of grain to be applied by the grain effect.
  37223. */
  37224. get: function () {
  37225. return this._grainIntensity;
  37226. },
  37227. set: function (value) {
  37228. if (this._grainIntensity === value) {
  37229. return;
  37230. }
  37231. this._grainIntensity = value;
  37232. },
  37233. enumerable: true,
  37234. configurable: true
  37235. });
  37236. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37237. /**
  37238. * If the grain effect should be animated.
  37239. */
  37240. get: function () {
  37241. return this._grainAnimated;
  37242. },
  37243. set: function (value) {
  37244. if (this._grainAnimated === value) {
  37245. return;
  37246. }
  37247. this._grainAnimated = value;
  37248. this._updateParameters();
  37249. },
  37250. enumerable: true,
  37251. configurable: true
  37252. });
  37253. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37254. /**
  37255. * Gets the vignette blend mode allowing different kind of effect.
  37256. */
  37257. get: function () {
  37258. return this._vignetteBlendMode;
  37259. },
  37260. /**
  37261. * Sets the vignette blend mode allowing different kind of effect.
  37262. */
  37263. set: function (value) {
  37264. if (this._vignetteBlendMode === value) {
  37265. return;
  37266. }
  37267. this._vignetteBlendMode = value;
  37268. this._updateParameters();
  37269. },
  37270. enumerable: true,
  37271. configurable: true
  37272. });
  37273. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37274. /**
  37275. * Gets wether the vignette effect is enabled.
  37276. */
  37277. get: function () {
  37278. return this._vignetteEnabled;
  37279. },
  37280. /**
  37281. * Sets wether the vignette effect is enabled.
  37282. */
  37283. set: function (value) {
  37284. if (this._vignetteEnabled === value) {
  37285. return;
  37286. }
  37287. this._vignetteEnabled = value;
  37288. this._updateParameters();
  37289. },
  37290. enumerable: true,
  37291. configurable: true
  37292. });
  37293. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37294. /**
  37295. * Gets wether the image processing is applied through a post process or not.
  37296. */
  37297. get: function () {
  37298. return this._applyByPostProcess;
  37299. },
  37300. /**
  37301. * Sets wether the image processing is applied through a post process or not.
  37302. */
  37303. set: function (value) {
  37304. if (this._applyByPostProcess === value) {
  37305. return;
  37306. }
  37307. this._applyByPostProcess = value;
  37308. this._updateParameters();
  37309. },
  37310. enumerable: true,
  37311. configurable: true
  37312. });
  37313. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37314. /**
  37315. * Gets wether the image processing is enabled or not.
  37316. */
  37317. get: function () {
  37318. return this._isEnabled;
  37319. },
  37320. /**
  37321. * Sets wether the image processing is enabled or not.
  37322. */
  37323. set: function (value) {
  37324. if (this._isEnabled === value) {
  37325. return;
  37326. }
  37327. this._isEnabled = value;
  37328. this._updateParameters();
  37329. },
  37330. enumerable: true,
  37331. configurable: true
  37332. });
  37333. /**
  37334. * Method called each time the image processing information changes requires to recompile the effect.
  37335. */
  37336. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37337. this.onUpdateParameters.notifyObservers(this);
  37338. };
  37339. ImageProcessingConfiguration.prototype.getClassName = function () {
  37340. return "ImageProcessingConfiguration";
  37341. };
  37342. /**
  37343. * Prepare the list of uniforms associated with the Image Processing effects.
  37344. * @param uniformsList The list of uniforms used in the effect
  37345. * @param defines the list of defines currently in use
  37346. */
  37347. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37348. if (defines.EXPOSURE) {
  37349. uniforms.push("exposureLinear");
  37350. }
  37351. if (defines.CONTRAST) {
  37352. uniforms.push("contrast");
  37353. }
  37354. if (defines.COLORGRADING) {
  37355. uniforms.push("colorTransformSettings");
  37356. }
  37357. if (defines.VIGNETTE) {
  37358. uniforms.push("vInverseScreenSize");
  37359. uniforms.push("vignetteSettings1");
  37360. uniforms.push("vignetteSettings2");
  37361. }
  37362. if (defines.COLORCURVES) {
  37363. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37364. }
  37365. if (defines.GRAIN) {
  37366. uniforms.push("grainVarianceAmount");
  37367. uniforms.push("grainAnimatedSeed");
  37368. }
  37369. };
  37370. /**
  37371. * Prepare the list of samplers associated with the Image Processing effects.
  37372. * @param uniformsList The list of uniforms used in the effect
  37373. * @param defines the list of defines currently in use
  37374. */
  37375. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37376. if (defines.COLORGRADING) {
  37377. samplersList.push("txColorTransform");
  37378. }
  37379. };
  37380. /**
  37381. * Prepare the list of defines associated to the shader.
  37382. * @param defines the list of defines to complete
  37383. */
  37384. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37385. if (forPostProcess === void 0) { forPostProcess = false; }
  37386. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37387. defines.VIGNETTE = false;
  37388. defines.TONEMAPPING = false;
  37389. defines.CONTRAST = false;
  37390. defines.EXPOSURE = false;
  37391. defines.COLORCURVES = false;
  37392. defines.COLORGRADING = false;
  37393. defines.COLORGRADING3D = false;
  37394. defines.IMAGEPROCESSING = false;
  37395. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37396. return;
  37397. }
  37398. defines.VIGNETTE = this.vignetteEnabled;
  37399. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37400. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37401. defines.TONEMAPPING = this.toneMappingEnabled;
  37402. defines.CONTRAST = (this.contrast !== 1.0);
  37403. defines.EXPOSURE = (this.exposure !== 1.0);
  37404. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37405. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37406. if (defines.COLORGRADING) {
  37407. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37408. }
  37409. else {
  37410. defines.COLORGRADING3D = false;
  37411. }
  37412. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37413. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37414. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37415. defines.GRAIN = this.grainEnabled;
  37416. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37417. };
  37418. /**
  37419. * Returns true if all the image processing information are ready.
  37420. */
  37421. ImageProcessingConfiguration.prototype.isReady = function () {
  37422. // Color Grading texure can not be none blocking.
  37423. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37424. };
  37425. /**
  37426. * Binds the image processing to the shader.
  37427. * @param effect The effect to bind to
  37428. */
  37429. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37430. if (aspectRatio === void 0) { aspectRatio = 1; }
  37431. // Color Curves
  37432. if (this._colorCurvesEnabled && this.colorCurves) {
  37433. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37434. }
  37435. // Vignette
  37436. if (this._vignetteEnabled) {
  37437. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37438. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37439. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37440. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37441. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37442. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37443. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37444. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37445. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37446. var vignettePower = -2.0 * this.vignetteWeight;
  37447. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37448. }
  37449. // Exposure
  37450. effect.setFloat("exposureLinear", this.exposure);
  37451. // Contrast
  37452. effect.setFloat("contrast", this.contrast);
  37453. // Color transform settings
  37454. if (this.colorGradingTexture) {
  37455. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37456. var textureSize = this.colorGradingTexture.getSize().height;
  37457. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37458. 0.5 / textureSize, // textureOffset
  37459. textureSize, // textureSize
  37460. this.colorGradingTexture.level // weight
  37461. );
  37462. }
  37463. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37464. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37465. };
  37466. /**
  37467. * Clones the current image processing instance.
  37468. * @return The cloned image processing
  37469. */
  37470. ImageProcessingConfiguration.prototype.clone = function () {
  37471. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37472. };
  37473. /**
  37474. * Serializes the current image processing instance to a json representation.
  37475. * @return a JSON representation
  37476. */
  37477. ImageProcessingConfiguration.prototype.serialize = function () {
  37478. return BABYLON.SerializationHelper.Serialize(this);
  37479. };
  37480. /**
  37481. * Parses the image processing from a json representation.
  37482. * @param source the JSON source to parse
  37483. * @return The parsed image processing
  37484. */
  37485. ImageProcessingConfiguration.Parse = function (source) {
  37486. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37487. };
  37488. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37489. /**
  37490. * Used to apply the vignette as a mix with the pixel color.
  37491. */
  37492. get: function () {
  37493. return this._VIGNETTEMODE_MULTIPLY;
  37494. },
  37495. enumerable: true,
  37496. configurable: true
  37497. });
  37498. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37499. /**
  37500. * Used to apply the vignette as a replacement of the pixel color.
  37501. */
  37502. get: function () {
  37503. return this._VIGNETTEMODE_OPAQUE;
  37504. },
  37505. enumerable: true,
  37506. configurable: true
  37507. });
  37508. // Static constants associated to the image processing.
  37509. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37510. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37511. __decorate([
  37512. BABYLON.serializeAsColorCurves()
  37513. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37514. __decorate([
  37515. BABYLON.serialize()
  37516. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37517. __decorate([
  37518. BABYLON.serializeAsTexture()
  37519. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37520. __decorate([
  37521. BABYLON.serialize()
  37522. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37523. __decorate([
  37524. BABYLON.serialize()
  37525. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37526. __decorate([
  37527. BABYLON.serialize()
  37528. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37529. __decorate([
  37530. BABYLON.serialize()
  37531. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37532. __decorate([
  37533. BABYLON.serialize()
  37534. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37535. __decorate([
  37536. BABYLON.serialize()
  37537. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37538. __decorate([
  37539. BABYLON.serialize()
  37540. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37541. __decorate([
  37542. BABYLON.serialize()
  37543. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37544. __decorate([
  37545. BABYLON.serialize()
  37546. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37547. __decorate([
  37548. BABYLON.serialize()
  37549. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37550. __decorate([
  37551. BABYLON.serializeAsColor4()
  37552. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37553. __decorate([
  37554. BABYLON.serialize()
  37555. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37556. __decorate([
  37557. BABYLON.serialize()
  37558. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37559. __decorate([
  37560. BABYLON.serialize()
  37561. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37562. __decorate([
  37563. BABYLON.serialize()
  37564. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37565. __decorate([
  37566. BABYLON.serialize()
  37567. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37568. __decorate([
  37569. BABYLON.serialize()
  37570. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37571. __decorate([
  37572. BABYLON.serialize()
  37573. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37574. __decorate([
  37575. BABYLON.serialize()
  37576. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37577. return ImageProcessingConfiguration;
  37578. }());
  37579. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37580. })(BABYLON || (BABYLON = {}));
  37581. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37582. var BABYLON;
  37583. (function (BABYLON) {
  37584. /**
  37585. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37586. * It can help converting any input color in a desired output one. This can then be used to create effects
  37587. * from sepia, black and white to sixties or futuristic rendering...
  37588. *
  37589. * The only supported format is currently 3dl.
  37590. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37591. */
  37592. var ColorGradingTexture = /** @class */ (function (_super) {
  37593. __extends(ColorGradingTexture, _super);
  37594. /**
  37595. * Instantiates a ColorGradingTexture from the following parameters.
  37596. *
  37597. * @param url The location of the color gradind data (currently only supporting 3dl)
  37598. * @param scene The scene the texture will be used in
  37599. */
  37600. function ColorGradingTexture(url, scene) {
  37601. var _this = _super.call(this, scene) || this;
  37602. if (!url) {
  37603. return _this;
  37604. }
  37605. _this._engine = scene.getEngine();
  37606. _this._textureMatrix = BABYLON.Matrix.Identity();
  37607. _this.name = url;
  37608. _this.url = url;
  37609. _this.hasAlpha = false;
  37610. _this.isCube = false;
  37611. _this.is3D = _this._engine.webGLVersion > 1;
  37612. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37613. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37614. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37615. _this.anisotropicFilteringLevel = 1;
  37616. _this._texture = _this._getFromCache(url, true);
  37617. if (!_this._texture) {
  37618. if (!scene.useDelayedTextureLoading) {
  37619. _this.loadTexture();
  37620. }
  37621. else {
  37622. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37623. }
  37624. }
  37625. return _this;
  37626. }
  37627. /**
  37628. * Returns the texture matrix used in most of the material.
  37629. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37630. */
  37631. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37632. return this._textureMatrix;
  37633. };
  37634. /**
  37635. * Occurs when the file being loaded is a .3dl LUT file.
  37636. */
  37637. ColorGradingTexture.prototype.load3dlTexture = function () {
  37638. var engine = this._engine;
  37639. var texture;
  37640. if (engine.webGLVersion === 1) {
  37641. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37642. }
  37643. else {
  37644. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37645. }
  37646. this._texture = texture;
  37647. var callback = function (text) {
  37648. if (typeof text !== "string") {
  37649. return;
  37650. }
  37651. var data = null;
  37652. var tempData = null;
  37653. var line;
  37654. var lines = text.split('\n');
  37655. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37656. var maxColor = 0;
  37657. for (var i = 0; i < lines.length; i++) {
  37658. line = lines[i];
  37659. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37660. continue;
  37661. if (line.indexOf('#') === 0)
  37662. continue;
  37663. var words = line.split(" ");
  37664. if (size === 0) {
  37665. // Number of space + one
  37666. size = words.length;
  37667. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37668. tempData = new Float32Array(size * size * size * 4);
  37669. continue;
  37670. }
  37671. if (size != 0) {
  37672. var r = Math.max(parseInt(words[0]), 0);
  37673. var g = Math.max(parseInt(words[1]), 0);
  37674. var b = Math.max(parseInt(words[2]), 0);
  37675. maxColor = Math.max(r, maxColor);
  37676. maxColor = Math.max(g, maxColor);
  37677. maxColor = Math.max(b, maxColor);
  37678. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37679. if (tempData) {
  37680. tempData[pixelStorageIndex + 0] = r;
  37681. tempData[pixelStorageIndex + 1] = g;
  37682. tempData[pixelStorageIndex + 2] = b;
  37683. }
  37684. pixelIndexSlice++;
  37685. if (pixelIndexSlice % size == 0) {
  37686. pixelIndexH++;
  37687. pixelIndexSlice = 0;
  37688. if (pixelIndexH % size == 0) {
  37689. pixelIndexW++;
  37690. pixelIndexH = 0;
  37691. }
  37692. }
  37693. }
  37694. }
  37695. if (tempData && data) {
  37696. for (var i = 0; i < tempData.length; i++) {
  37697. if (i > 0 && (i + 1) % 4 === 0) {
  37698. data[i] = 255;
  37699. }
  37700. else {
  37701. var value = tempData[i];
  37702. data[i] = (value / maxColor * 255);
  37703. }
  37704. }
  37705. }
  37706. if (texture.is3D) {
  37707. texture.updateSize(size, size, size);
  37708. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37709. }
  37710. else {
  37711. texture.updateSize(size * size, size);
  37712. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37713. }
  37714. };
  37715. var scene = this.getScene();
  37716. if (scene) {
  37717. scene._loadFile(this.url, callback);
  37718. }
  37719. else {
  37720. this._engine._loadFile(this.url, callback);
  37721. }
  37722. return this._texture;
  37723. };
  37724. /**
  37725. * Starts the loading process of the texture.
  37726. */
  37727. ColorGradingTexture.prototype.loadTexture = function () {
  37728. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37729. this.load3dlTexture();
  37730. }
  37731. };
  37732. /**
  37733. * Clones the color gradind texture.
  37734. */
  37735. ColorGradingTexture.prototype.clone = function () {
  37736. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37737. // Base texture
  37738. newTexture.level = this.level;
  37739. return newTexture;
  37740. };
  37741. /**
  37742. * Called during delayed load for textures.
  37743. */
  37744. ColorGradingTexture.prototype.delayLoad = function () {
  37745. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37746. return;
  37747. }
  37748. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37749. this._texture = this._getFromCache(this.url, true);
  37750. if (!this._texture) {
  37751. this.loadTexture();
  37752. }
  37753. };
  37754. /**
  37755. * Parses a color grading texture serialized by Babylon.
  37756. * @param parsedTexture The texture information being parsedTexture
  37757. * @param scene The scene to load the texture in
  37758. * @param rootUrl The root url of the data assets to load
  37759. * @return A color gradind texture
  37760. */
  37761. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37762. var texture = null;
  37763. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37764. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37765. texture.name = parsedTexture.name;
  37766. texture.level = parsedTexture.level;
  37767. }
  37768. return texture;
  37769. };
  37770. /**
  37771. * Serializes the LUT texture to json format.
  37772. */
  37773. ColorGradingTexture.prototype.serialize = function () {
  37774. if (!this.name) {
  37775. return null;
  37776. }
  37777. var serializationObject = {};
  37778. serializationObject.name = this.name;
  37779. serializationObject.level = this.level;
  37780. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37781. return serializationObject;
  37782. };
  37783. /**
  37784. * Empty line regex stored for GC.
  37785. */
  37786. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37787. return ColorGradingTexture;
  37788. }(BABYLON.BaseTexture));
  37789. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37790. })(BABYLON || (BABYLON = {}));
  37791. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37792. var BABYLON;
  37793. (function (BABYLON) {
  37794. /**
  37795. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37796. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37797. * 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;
  37798. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37799. */
  37800. var ColorCurves = /** @class */ (function () {
  37801. function ColorCurves() {
  37802. this._dirty = true;
  37803. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37804. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37805. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37806. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37807. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37808. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37809. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37810. this._globalHue = 30;
  37811. this._globalDensity = 0;
  37812. this._globalSaturation = 0;
  37813. this._globalExposure = 0;
  37814. this._highlightsHue = 30;
  37815. this._highlightsDensity = 0;
  37816. this._highlightsSaturation = 0;
  37817. this._highlightsExposure = 0;
  37818. this._midtonesHue = 30;
  37819. this._midtonesDensity = 0;
  37820. this._midtonesSaturation = 0;
  37821. this._midtonesExposure = 0;
  37822. this._shadowsHue = 30;
  37823. this._shadowsDensity = 0;
  37824. this._shadowsSaturation = 0;
  37825. this._shadowsExposure = 0;
  37826. }
  37827. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37828. /**
  37829. * Gets the global Hue value.
  37830. * 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).
  37831. */
  37832. get: function () {
  37833. return this._globalHue;
  37834. },
  37835. /**
  37836. * Sets the global Hue value.
  37837. * 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).
  37838. */
  37839. set: function (value) {
  37840. this._globalHue = value;
  37841. this._dirty = true;
  37842. },
  37843. enumerable: true,
  37844. configurable: true
  37845. });
  37846. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37847. /**
  37848. * Gets the global Density value.
  37849. * 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.
  37850. * Values less than zero provide a filter of opposite hue.
  37851. */
  37852. get: function () {
  37853. return this._globalDensity;
  37854. },
  37855. /**
  37856. * Sets the global Density value.
  37857. * 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.
  37858. * Values less than zero provide a filter of opposite hue.
  37859. */
  37860. set: function (value) {
  37861. this._globalDensity = value;
  37862. this._dirty = true;
  37863. },
  37864. enumerable: true,
  37865. configurable: true
  37866. });
  37867. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37868. /**
  37869. * Gets the global Saturation value.
  37870. * 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.
  37871. */
  37872. get: function () {
  37873. return this._globalSaturation;
  37874. },
  37875. /**
  37876. * Sets the global Saturation value.
  37877. * 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.
  37878. */
  37879. set: function (value) {
  37880. this._globalSaturation = value;
  37881. this._dirty = true;
  37882. },
  37883. enumerable: true,
  37884. configurable: true
  37885. });
  37886. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37887. /**
  37888. * Gets the highlights Hue value.
  37889. * 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).
  37890. */
  37891. get: function () {
  37892. return this._highlightsHue;
  37893. },
  37894. /**
  37895. * Sets the highlights Hue value.
  37896. * 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).
  37897. */
  37898. set: function (value) {
  37899. this._highlightsHue = value;
  37900. this._dirty = true;
  37901. },
  37902. enumerable: true,
  37903. configurable: true
  37904. });
  37905. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37906. /**
  37907. * Gets the highlights Density value.
  37908. * 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.
  37909. * Values less than zero provide a filter of opposite hue.
  37910. */
  37911. get: function () {
  37912. return this._highlightsDensity;
  37913. },
  37914. /**
  37915. * Sets the highlights Density value.
  37916. * 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.
  37917. * Values less than zero provide a filter of opposite hue.
  37918. */
  37919. set: function (value) {
  37920. this._highlightsDensity = value;
  37921. this._dirty = true;
  37922. },
  37923. enumerable: true,
  37924. configurable: true
  37925. });
  37926. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37927. /**
  37928. * Gets the highlights Saturation value.
  37929. * 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.
  37930. */
  37931. get: function () {
  37932. return this._highlightsSaturation;
  37933. },
  37934. /**
  37935. * Sets the highlights Saturation value.
  37936. * 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.
  37937. */
  37938. set: function (value) {
  37939. this._highlightsSaturation = value;
  37940. this._dirty = true;
  37941. },
  37942. enumerable: true,
  37943. configurable: true
  37944. });
  37945. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37946. /**
  37947. * Gets the highlights Exposure value.
  37948. * 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.
  37949. */
  37950. get: function () {
  37951. return this._highlightsExposure;
  37952. },
  37953. /**
  37954. * Sets the highlights Exposure value.
  37955. * 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.
  37956. */
  37957. set: function (value) {
  37958. this._highlightsExposure = value;
  37959. this._dirty = true;
  37960. },
  37961. enumerable: true,
  37962. configurable: true
  37963. });
  37964. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37965. /**
  37966. * Gets the midtones Hue value.
  37967. * 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).
  37968. */
  37969. get: function () {
  37970. return this._midtonesHue;
  37971. },
  37972. /**
  37973. * Sets the midtones Hue value.
  37974. * 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).
  37975. */
  37976. set: function (value) {
  37977. this._midtonesHue = value;
  37978. this._dirty = true;
  37979. },
  37980. enumerable: true,
  37981. configurable: true
  37982. });
  37983. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37984. /**
  37985. * Gets the midtones Density value.
  37986. * 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.
  37987. * Values less than zero provide a filter of opposite hue.
  37988. */
  37989. get: function () {
  37990. return this._midtonesDensity;
  37991. },
  37992. /**
  37993. * Sets the midtones Density value.
  37994. * 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.
  37995. * Values less than zero provide a filter of opposite hue.
  37996. */
  37997. set: function (value) {
  37998. this._midtonesDensity = value;
  37999. this._dirty = true;
  38000. },
  38001. enumerable: true,
  38002. configurable: true
  38003. });
  38004. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38005. /**
  38006. * Gets the midtones Saturation value.
  38007. * 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.
  38008. */
  38009. get: function () {
  38010. return this._midtonesSaturation;
  38011. },
  38012. /**
  38013. * Sets the midtones Saturation value.
  38014. * 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.
  38015. */
  38016. set: function (value) {
  38017. this._midtonesSaturation = value;
  38018. this._dirty = true;
  38019. },
  38020. enumerable: true,
  38021. configurable: true
  38022. });
  38023. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38024. /**
  38025. * Gets the midtones Exposure value.
  38026. * 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.
  38027. */
  38028. get: function () {
  38029. return this._midtonesExposure;
  38030. },
  38031. /**
  38032. * Sets the midtones Exposure value.
  38033. * 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.
  38034. */
  38035. set: function (value) {
  38036. this._midtonesExposure = value;
  38037. this._dirty = true;
  38038. },
  38039. enumerable: true,
  38040. configurable: true
  38041. });
  38042. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38043. /**
  38044. * Gets the shadows Hue value.
  38045. * 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).
  38046. */
  38047. get: function () {
  38048. return this._shadowsHue;
  38049. },
  38050. /**
  38051. * Sets the shadows Hue value.
  38052. * 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).
  38053. */
  38054. set: function (value) {
  38055. this._shadowsHue = value;
  38056. this._dirty = true;
  38057. },
  38058. enumerable: true,
  38059. configurable: true
  38060. });
  38061. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38062. /**
  38063. * Gets the shadows Density value.
  38064. * 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.
  38065. * Values less than zero provide a filter of opposite hue.
  38066. */
  38067. get: function () {
  38068. return this._shadowsDensity;
  38069. },
  38070. /**
  38071. * Sets the shadows Density value.
  38072. * 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.
  38073. * Values less than zero provide a filter of opposite hue.
  38074. */
  38075. set: function (value) {
  38076. this._shadowsDensity = value;
  38077. this._dirty = true;
  38078. },
  38079. enumerable: true,
  38080. configurable: true
  38081. });
  38082. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38083. /**
  38084. * Gets the shadows Saturation value.
  38085. * 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.
  38086. */
  38087. get: function () {
  38088. return this._shadowsSaturation;
  38089. },
  38090. /**
  38091. * Sets the shadows Saturation value.
  38092. * 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.
  38093. */
  38094. set: function (value) {
  38095. this._shadowsSaturation = value;
  38096. this._dirty = true;
  38097. },
  38098. enumerable: true,
  38099. configurable: true
  38100. });
  38101. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38102. /**
  38103. * Gets the shadows Exposure value.
  38104. * 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.
  38105. */
  38106. get: function () {
  38107. return this._shadowsExposure;
  38108. },
  38109. /**
  38110. * Sets the shadows Exposure value.
  38111. * 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.
  38112. */
  38113. set: function (value) {
  38114. this._shadowsExposure = value;
  38115. this._dirty = true;
  38116. },
  38117. enumerable: true,
  38118. configurable: true
  38119. });
  38120. ColorCurves.prototype.getClassName = function () {
  38121. return "ColorCurves";
  38122. };
  38123. /**
  38124. * Binds the color curves to the shader.
  38125. * @param colorCurves The color curve to bind
  38126. * @param effect The effect to bind to
  38127. */
  38128. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38129. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38130. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38131. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38132. if (colorCurves._dirty) {
  38133. colorCurves._dirty = false;
  38134. // Fill in global info.
  38135. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38136. // Compute highlights info.
  38137. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38138. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38139. // Compute midtones info.
  38140. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38141. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38142. // Compute shadows info.
  38143. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38144. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38145. // Compute deltas (neutral is midtones).
  38146. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38147. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38148. }
  38149. if (effect) {
  38150. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38151. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38152. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38153. }
  38154. };
  38155. /**
  38156. * Prepare the list of uniforms associated with the ColorCurves effects.
  38157. * @param uniformsList The list of uniforms used in the effect
  38158. */
  38159. ColorCurves.PrepareUniforms = function (uniformsList) {
  38160. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38161. };
  38162. /**
  38163. * Returns color grading data based on a hue, density, saturation and exposure value.
  38164. * @param filterHue The hue of the color filter.
  38165. * @param filterDensity The density of the color filter.
  38166. * @param saturation The saturation.
  38167. * @param exposure The exposure.
  38168. * @param result The result data container.
  38169. */
  38170. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38171. if (hue == null) {
  38172. return;
  38173. }
  38174. hue = ColorCurves.clamp(hue, 0, 360);
  38175. density = ColorCurves.clamp(density, -100, 100);
  38176. saturation = ColorCurves.clamp(saturation, -100, 100);
  38177. exposure = ColorCurves.clamp(exposure, -100, 100);
  38178. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38179. // so that the maximum filter density is only 50% control. This provides fine control
  38180. // for small values and reasonable range.
  38181. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38182. density *= 0.5;
  38183. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38184. if (density < 0) {
  38185. density *= -1;
  38186. hue = (hue + 180) % 360;
  38187. }
  38188. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38189. result.scaleToRef(2, result);
  38190. result.a = 1 + 0.01 * saturation;
  38191. };
  38192. /**
  38193. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38194. * @param value The input slider value in range [-100,100].
  38195. * @returns Adjusted value.
  38196. */
  38197. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38198. value /= 100;
  38199. var x = Math.abs(value);
  38200. x = Math.pow(x, 2);
  38201. if (value < 0) {
  38202. x *= -1;
  38203. }
  38204. x *= 100;
  38205. return x;
  38206. };
  38207. /**
  38208. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38209. * @param hue The hue (H) input.
  38210. * @param saturation The saturation (S) input.
  38211. * @param brightness The brightness (B) input.
  38212. * @result An RGBA color represented as Vector4.
  38213. */
  38214. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38215. var h = ColorCurves.clamp(hue, 0, 360);
  38216. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38217. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38218. if (s === 0) {
  38219. result.r = v;
  38220. result.g = v;
  38221. result.b = v;
  38222. }
  38223. else {
  38224. // sector 0 to 5
  38225. h /= 60;
  38226. var i = Math.floor(h);
  38227. // fractional part of h
  38228. var f = h - i;
  38229. var p = v * (1 - s);
  38230. var q = v * (1 - s * f);
  38231. var t = v * (1 - s * (1 - f));
  38232. switch (i) {
  38233. case 0:
  38234. result.r = v;
  38235. result.g = t;
  38236. result.b = p;
  38237. break;
  38238. case 1:
  38239. result.r = q;
  38240. result.g = v;
  38241. result.b = p;
  38242. break;
  38243. case 2:
  38244. result.r = p;
  38245. result.g = v;
  38246. result.b = t;
  38247. break;
  38248. case 3:
  38249. result.r = p;
  38250. result.g = q;
  38251. result.b = v;
  38252. break;
  38253. case 4:
  38254. result.r = t;
  38255. result.g = p;
  38256. result.b = v;
  38257. break;
  38258. default:// case 5:
  38259. result.r = v;
  38260. result.g = p;
  38261. result.b = q;
  38262. break;
  38263. }
  38264. }
  38265. result.a = 1;
  38266. };
  38267. /**
  38268. * Returns a value clamped between min and max
  38269. * @param value The value to clamp
  38270. * @param min The minimum of value
  38271. * @param max The maximum of value
  38272. * @returns The clamped value.
  38273. */
  38274. ColorCurves.clamp = function (value, min, max) {
  38275. return Math.min(Math.max(value, min), max);
  38276. };
  38277. /**
  38278. * Clones the current color curve instance.
  38279. * @return The cloned curves
  38280. */
  38281. ColorCurves.prototype.clone = function () {
  38282. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38283. };
  38284. /**
  38285. * Serializes the current color curve instance to a json representation.
  38286. * @return a JSON representation
  38287. */
  38288. ColorCurves.prototype.serialize = function () {
  38289. return BABYLON.SerializationHelper.Serialize(this);
  38290. };
  38291. /**
  38292. * Parses the color curve from a json representation.
  38293. * @param source the JSON source to parse
  38294. * @return The parsed curves
  38295. */
  38296. ColorCurves.Parse = function (source) {
  38297. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38298. };
  38299. __decorate([
  38300. BABYLON.serialize()
  38301. ], ColorCurves.prototype, "_globalHue", void 0);
  38302. __decorate([
  38303. BABYLON.serialize()
  38304. ], ColorCurves.prototype, "_globalDensity", void 0);
  38305. __decorate([
  38306. BABYLON.serialize()
  38307. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38308. __decorate([
  38309. BABYLON.serialize()
  38310. ], ColorCurves.prototype, "_globalExposure", void 0);
  38311. __decorate([
  38312. BABYLON.serialize()
  38313. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38314. __decorate([
  38315. BABYLON.serialize()
  38316. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38317. __decorate([
  38318. BABYLON.serialize()
  38319. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38320. __decorate([
  38321. BABYLON.serialize()
  38322. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38323. __decorate([
  38324. BABYLON.serialize()
  38325. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38326. __decorate([
  38327. BABYLON.serialize()
  38328. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38329. __decorate([
  38330. BABYLON.serialize()
  38331. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38332. __decorate([
  38333. BABYLON.serialize()
  38334. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38335. return ColorCurves;
  38336. }());
  38337. BABYLON.ColorCurves = ColorCurves;
  38338. })(BABYLON || (BABYLON = {}));
  38339. //# sourceMappingURL=babylon.colorCurves.js.map
  38340. //# sourceMappingURL=babylon.behavior.js.map
  38341. var BABYLON;
  38342. (function (BABYLON) {
  38343. /**
  38344. * "Static Class" containing the most commonly used helper while dealing with material for
  38345. * rendering purpose.
  38346. *
  38347. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38348. *
  38349. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38350. */
  38351. var MaterialHelper = /** @class */ (function () {
  38352. function MaterialHelper() {
  38353. }
  38354. /**
  38355. * Bind the current view position to an effect.
  38356. * @param effect The effect to be bound
  38357. * @param scene The scene the eyes position is used from
  38358. */
  38359. MaterialHelper.BindEyePosition = function (effect, scene) {
  38360. if (scene._forcedViewPosition) {
  38361. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38362. return;
  38363. }
  38364. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38365. };
  38366. /**
  38367. * Helps preparing the defines values about the UVs in used in the effect.
  38368. * UVs are shared as much as we can accross chanels in the shaders.
  38369. * @param texture The texture we are preparing the UVs for
  38370. * @param defines The defines to update
  38371. * @param key The chanel key "diffuse", "specular"... used in the shader
  38372. */
  38373. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38374. defines._needUVs = true;
  38375. defines[key] = true;
  38376. if (texture.getTextureMatrix().isIdentity(true)) {
  38377. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38378. if (texture.coordinatesIndex === 0) {
  38379. defines["MAINUV1"] = true;
  38380. }
  38381. else {
  38382. defines["MAINUV2"] = true;
  38383. }
  38384. }
  38385. else {
  38386. defines[key + "DIRECTUV"] = 0;
  38387. }
  38388. };
  38389. /**
  38390. * Binds a texture matrix value to its corrsponding uniform
  38391. * @param texture The texture to bind the matrix for
  38392. * @param uniformBuffer The uniform buffer receivin the data
  38393. * @param key The chanel key "diffuse", "specular"... used in the shader
  38394. */
  38395. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38396. var matrix = texture.getTextureMatrix();
  38397. if (!matrix.isIdentity(true)) {
  38398. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38399. }
  38400. };
  38401. /**
  38402. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38403. * @param mesh defines the current mesh
  38404. * @param scene defines the current scene
  38405. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38406. * @param pointsCloud defines if point cloud rendering has to be turned on
  38407. * @param fogEnabled defines if fog has to be turned on
  38408. * @param alphaTest defines if alpha testing has to be turned on
  38409. * @param defines defines the current list of defines
  38410. */
  38411. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38412. if (defines._areMiscDirty) {
  38413. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38414. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38415. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38416. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38417. defines["ALPHATEST"] = alphaTest;
  38418. }
  38419. };
  38420. /**
  38421. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38422. * @param scene defines the current scene
  38423. * @param engine defines the current engine
  38424. * @param defines specifies the list of active defines
  38425. * @param useInstances defines if instances have to be turned on
  38426. * @param useClipPlane defines if clip plane have to be turned on
  38427. */
  38428. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38429. if (useClipPlane === void 0) { useClipPlane = null; }
  38430. var changed = false;
  38431. if (useClipPlane == null) {
  38432. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38433. }
  38434. if (defines["CLIPPLANE"] !== useClipPlane) {
  38435. defines["CLIPPLANE"] = useClipPlane;
  38436. changed = true;
  38437. }
  38438. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38439. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38440. changed = true;
  38441. }
  38442. if (defines["INSTANCES"] !== useInstances) {
  38443. defines["INSTANCES"] = useInstances;
  38444. changed = true;
  38445. }
  38446. if (changed) {
  38447. defines.markAsUnprocessed();
  38448. }
  38449. };
  38450. /**
  38451. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38452. * @param mesh The mesh containing the geometry data we will draw
  38453. * @param defines The defines to update
  38454. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38455. * @param useBones Precise whether bones should be used or not (override mesh info)
  38456. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38457. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38458. * @returns false if defines are considered not dirty and have not been checked
  38459. */
  38460. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38461. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38462. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38463. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38464. return false;
  38465. }
  38466. defines._normals = defines._needNormals;
  38467. defines._uvs = defines._needUVs;
  38468. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38469. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38470. defines["TANGENT"] = true;
  38471. }
  38472. if (defines._needUVs) {
  38473. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38474. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38475. }
  38476. else {
  38477. defines["UV1"] = false;
  38478. defines["UV2"] = false;
  38479. }
  38480. if (useVertexColor) {
  38481. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38482. defines["VERTEXCOLOR"] = hasVertexColors;
  38483. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38484. }
  38485. if (useBones) {
  38486. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38487. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38488. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38489. }
  38490. else {
  38491. defines["NUM_BONE_INFLUENCERS"] = 0;
  38492. defines["BonesPerMesh"] = 0;
  38493. }
  38494. }
  38495. if (useMorphTargets) {
  38496. var manager = mesh.morphTargetManager;
  38497. if (manager) {
  38498. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38499. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38500. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38501. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38502. }
  38503. else {
  38504. defines["MORPHTARGETS_TANGENT"] = false;
  38505. defines["MORPHTARGETS_NORMAL"] = false;
  38506. defines["MORPHTARGETS"] = false;
  38507. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38508. }
  38509. }
  38510. return true;
  38511. };
  38512. /**
  38513. * Prepares the defines related to the light information passed in parameter
  38514. * @param scene The scene we are intending to draw
  38515. * @param mesh The mesh the effect is compiling for
  38516. * @param defines The defines to update
  38517. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38518. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38519. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38520. * @returns true if normals will be required for the rest of the effect
  38521. */
  38522. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38523. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38524. if (disableLighting === void 0) { disableLighting = false; }
  38525. if (!defines._areLightsDirty) {
  38526. return defines._needNormals;
  38527. }
  38528. var lightIndex = 0;
  38529. var needNormals = false;
  38530. var needRebuild = false;
  38531. var lightmapMode = false;
  38532. var shadowEnabled = false;
  38533. var specularEnabled = false;
  38534. if (scene.lightsEnabled && !disableLighting) {
  38535. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38536. var light = _a[_i];
  38537. needNormals = true;
  38538. if (defines["LIGHT" + lightIndex] === undefined) {
  38539. needRebuild = true;
  38540. }
  38541. defines["LIGHT" + lightIndex] = true;
  38542. defines["SPOTLIGHT" + lightIndex] = false;
  38543. defines["HEMILIGHT" + lightIndex] = false;
  38544. defines["POINTLIGHT" + lightIndex] = false;
  38545. defines["DIRLIGHT" + lightIndex] = false;
  38546. var type;
  38547. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38548. type = "SPOTLIGHT" + lightIndex;
  38549. var spotLight = light;
  38550. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38551. }
  38552. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38553. type = "HEMILIGHT" + lightIndex;
  38554. }
  38555. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38556. type = "POINTLIGHT" + lightIndex;
  38557. }
  38558. else {
  38559. type = "DIRLIGHT" + lightIndex;
  38560. }
  38561. defines[type] = true;
  38562. // Specular
  38563. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38564. specularEnabled = true;
  38565. }
  38566. // Shadows
  38567. defines["SHADOW" + lightIndex] = false;
  38568. defines["SHADOWPCF" + lightIndex] = false;
  38569. defines["SHADOWESM" + lightIndex] = false;
  38570. defines["SHADOWCUBE" + lightIndex] = false;
  38571. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38572. var shadowGenerator = light.getShadowGenerator();
  38573. if (shadowGenerator) {
  38574. shadowEnabled = true;
  38575. shadowGenerator.prepareDefines(defines, lightIndex);
  38576. }
  38577. }
  38578. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38579. lightmapMode = true;
  38580. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38581. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38582. }
  38583. else {
  38584. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38585. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38586. }
  38587. lightIndex++;
  38588. if (lightIndex === maxSimultaneousLights)
  38589. break;
  38590. }
  38591. }
  38592. defines["SPECULARTERM"] = specularEnabled;
  38593. defines["SHADOWS"] = shadowEnabled;
  38594. // Resetting all other lights if any
  38595. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38596. if (defines["LIGHT" + index] !== undefined) {
  38597. defines["LIGHT" + index] = false;
  38598. defines["HEMILIGHT" + lightIndex] = false;
  38599. defines["POINTLIGHT" + lightIndex] = false;
  38600. defines["DIRLIGHT" + lightIndex] = false;
  38601. defines["SPOTLIGHT" + lightIndex] = false;
  38602. defines["SHADOW" + lightIndex] = false;
  38603. }
  38604. }
  38605. var caps = scene.getEngine().getCaps();
  38606. if (defines["SHADOWFLOAT"] === undefined) {
  38607. needRebuild = true;
  38608. }
  38609. defines["SHADOWFLOAT"] = shadowEnabled &&
  38610. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38611. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38612. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38613. if (needRebuild) {
  38614. defines.rebuild();
  38615. }
  38616. return needNormals;
  38617. };
  38618. /**
  38619. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38620. * that won t be acctive due to defines being turned off.
  38621. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38622. * @param samplersList The samplers list
  38623. * @param defines The defines helping in the list generation
  38624. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38625. */
  38626. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38627. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38628. var uniformsList;
  38629. var uniformBuffersList = null;
  38630. if (uniformsListOrOptions.uniformsNames) {
  38631. var options = uniformsListOrOptions;
  38632. uniformsList = options.uniformsNames;
  38633. uniformBuffersList = options.uniformBuffersNames;
  38634. samplersList = options.samplers;
  38635. defines = options.defines;
  38636. maxSimultaneousLights = options.maxSimultaneousLights;
  38637. }
  38638. else {
  38639. uniformsList = uniformsListOrOptions;
  38640. if (!samplersList) {
  38641. samplersList = [];
  38642. }
  38643. }
  38644. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38645. if (!defines["LIGHT" + lightIndex]) {
  38646. break;
  38647. }
  38648. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38649. if (uniformBuffersList) {
  38650. uniformBuffersList.push("Light" + lightIndex);
  38651. }
  38652. samplersList.push("shadowSampler" + lightIndex);
  38653. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38654. samplersList.push("projectionLightSampler" + lightIndex);
  38655. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38656. }
  38657. }
  38658. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38659. uniformsList.push("morphTargetInfluences");
  38660. }
  38661. };
  38662. /**
  38663. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38664. * @param defines The defines to update while falling back
  38665. * @param fallbacks The authorized effect fallbacks
  38666. * @param maxSimultaneousLights The maximum number of lights allowed
  38667. * @param rank the current rank of the Effect
  38668. * @returns The newly affected rank
  38669. */
  38670. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38671. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38672. if (rank === void 0) { rank = 0; }
  38673. var lightFallbackRank = 0;
  38674. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38675. if (!defines["LIGHT" + lightIndex]) {
  38676. break;
  38677. }
  38678. if (lightIndex > 0) {
  38679. lightFallbackRank = rank + lightIndex;
  38680. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38681. }
  38682. if (!defines["SHADOWS"]) {
  38683. if (defines["SHADOW" + lightIndex]) {
  38684. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38685. }
  38686. if (defines["SHADOWPCF" + lightIndex]) {
  38687. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38688. }
  38689. if (defines["SHADOWESM" + lightIndex]) {
  38690. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38691. }
  38692. }
  38693. }
  38694. return lightFallbackRank++;
  38695. };
  38696. /**
  38697. * Prepares the list of attributes required for morph targets according to the effect defines.
  38698. * @param attribs The current list of supported attribs
  38699. * @param mesh The mesh to prepare the morph targets attributes for
  38700. * @param defines The current Defines of the effect
  38701. */
  38702. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38703. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38704. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38705. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38706. var manager = mesh.morphTargetManager;
  38707. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38708. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38709. for (var index = 0; index < influencers; index++) {
  38710. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38711. if (normal) {
  38712. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38713. }
  38714. if (tangent) {
  38715. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38716. }
  38717. if (attribs.length > maxAttributesCount) {
  38718. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38719. }
  38720. }
  38721. }
  38722. };
  38723. /**
  38724. * Prepares the list of attributes required for bones according to the effect defines.
  38725. * @param attribs The current list of supported attribs
  38726. * @param mesh The mesh to prepare the bones attributes for
  38727. * @param defines The current Defines of the effect
  38728. * @param fallbacks The current efffect fallback strategy
  38729. */
  38730. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38731. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38732. fallbacks.addCPUSkinningFallback(0, mesh);
  38733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38735. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38738. }
  38739. }
  38740. };
  38741. /**
  38742. * Prepares the list of attributes required for instances according to the effect defines.
  38743. * @param attribs The current list of supported attribs
  38744. * @param defines The current Defines of the effect
  38745. */
  38746. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38747. if (defines["INSTANCES"]) {
  38748. attribs.push("world0");
  38749. attribs.push("world1");
  38750. attribs.push("world2");
  38751. attribs.push("world3");
  38752. }
  38753. };
  38754. /**
  38755. * Binds the light shadow information to the effect for the given mesh.
  38756. * @param light The light containing the generator
  38757. * @param scene The scene the lights belongs to
  38758. * @param mesh The mesh we are binding the information to render
  38759. * @param lightIndex The light index in the effect used to render the mesh
  38760. * @param effect The effect we are binding the data to
  38761. */
  38762. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38763. if (light.shadowEnabled && mesh.receiveShadows) {
  38764. var shadowGenerator = light.getShadowGenerator();
  38765. if (shadowGenerator) {
  38766. shadowGenerator.bindShadowLight(lightIndex, effect);
  38767. }
  38768. }
  38769. };
  38770. /**
  38771. * Binds the light information to the effect.
  38772. * @param light The light containing the generator
  38773. * @param effect The effect we are binding the data to
  38774. * @param lightIndex The light index in the effect used to render
  38775. */
  38776. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38777. light.transferToEffect(effect, lightIndex + "");
  38778. };
  38779. /**
  38780. * Binds the lights information from the scene to the effect for the given mesh.
  38781. * @param scene The scene the lights belongs to
  38782. * @param mesh The mesh we are binding the information to render
  38783. * @param effect The effect we are binding the data to
  38784. * @param defines The generated defines for the effect
  38785. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38786. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38787. */
  38788. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38789. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38790. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38791. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38792. for (var i = 0; i < len; i++) {
  38793. var light = mesh._lightSources[i];
  38794. var iAsString = i.toString();
  38795. var scaledIntensity = light.getScaledIntensity();
  38796. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38797. MaterialHelper.BindLightProperties(light, effect, i);
  38798. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38799. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38800. if (defines["SPECULARTERM"]) {
  38801. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38802. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38803. }
  38804. // Shadows
  38805. if (scene.shadowsEnabled) {
  38806. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38807. }
  38808. light._uniformBuffer.update();
  38809. }
  38810. };
  38811. /**
  38812. * Binds the fog information from the scene to the effect for the given mesh.
  38813. * @param scene The scene the lights belongs to
  38814. * @param mesh The mesh we are binding the information to render
  38815. * @param effect The effect we are binding the data to
  38816. */
  38817. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38818. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38819. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38820. effect.setColor3("vFogColor", scene.fogColor);
  38821. }
  38822. };
  38823. /**
  38824. * Binds the bones information from the mesh to the effect.
  38825. * @param mesh The mesh we are binding the information to render
  38826. * @param effect The effect we are binding the data to
  38827. */
  38828. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38829. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38830. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38831. if (matrices && effect) {
  38832. effect.setMatrices("mBones", matrices);
  38833. }
  38834. }
  38835. };
  38836. /**
  38837. * Binds the morph targets information from the mesh to the effect.
  38838. * @param abstractMesh The mesh we are binding the information to render
  38839. * @param effect The effect we are binding the data to
  38840. */
  38841. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38842. var manager = abstractMesh.morphTargetManager;
  38843. if (!abstractMesh || !manager) {
  38844. return;
  38845. }
  38846. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38847. };
  38848. /**
  38849. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38850. * @param defines The generated defines used in the effect
  38851. * @param effect The effect we are binding the data to
  38852. * @param scene The scene we are willing to render with logarithmic scale for
  38853. */
  38854. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38855. if (defines["LOGARITHMICDEPTH"]) {
  38856. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38857. }
  38858. };
  38859. /**
  38860. * Binds the clip plane information from the scene to the effect.
  38861. * @param scene The scene the clip plane information are extracted from
  38862. * @param effect The effect we are binding the data to
  38863. */
  38864. MaterialHelper.BindClipPlane = function (effect, scene) {
  38865. if (scene.clipPlane) {
  38866. var clipPlane = scene.clipPlane;
  38867. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38868. }
  38869. };
  38870. return MaterialHelper;
  38871. }());
  38872. BABYLON.MaterialHelper = MaterialHelper;
  38873. })(BABYLON || (BABYLON = {}));
  38874. //# sourceMappingURL=babylon.materialHelper.js.map
  38875. var BABYLON;
  38876. (function (BABYLON) {
  38877. var PushMaterial = /** @class */ (function (_super) {
  38878. __extends(PushMaterial, _super);
  38879. function PushMaterial(name, scene) {
  38880. var _this = _super.call(this, name, scene) || this;
  38881. _this._normalMatrix = new BABYLON.Matrix();
  38882. _this.storeEffectOnSubMeshes = true;
  38883. return _this;
  38884. }
  38885. PushMaterial.prototype.getEffect = function () {
  38886. return this._activeEffect;
  38887. };
  38888. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38889. if (!mesh) {
  38890. return false;
  38891. }
  38892. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38893. return true;
  38894. }
  38895. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38896. };
  38897. /**
  38898. * Binds the given world matrix to the active effect
  38899. *
  38900. * @param world the matrix to bind
  38901. */
  38902. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38903. this._activeEffect.setMatrix("world", world);
  38904. };
  38905. /**
  38906. * Binds the given normal matrix to the active effect
  38907. *
  38908. * @param normalMatrix the matrix to bind
  38909. */
  38910. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38911. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38912. };
  38913. PushMaterial.prototype.bind = function (world, mesh) {
  38914. if (!mesh) {
  38915. return;
  38916. }
  38917. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38918. };
  38919. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38920. if (effect === void 0) { effect = null; }
  38921. _super.prototype._afterBind.call(this, mesh);
  38922. this.getScene()._cachedEffect = effect;
  38923. };
  38924. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38925. if (visibility === void 0) { visibility = 1; }
  38926. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38927. };
  38928. return PushMaterial;
  38929. }(BABYLON.Material));
  38930. BABYLON.PushMaterial = PushMaterial;
  38931. })(BABYLON || (BABYLON = {}));
  38932. //# sourceMappingURL=babylon.pushMaterial.js.map
  38933. var BABYLON;
  38934. (function (BABYLON) {
  38935. /** @ignore */
  38936. var StandardMaterialDefines = /** @class */ (function (_super) {
  38937. __extends(StandardMaterialDefines, _super);
  38938. function StandardMaterialDefines() {
  38939. var _this = _super.call(this) || this;
  38940. _this.MAINUV1 = false;
  38941. _this.MAINUV2 = false;
  38942. _this.DIFFUSE = false;
  38943. _this.DIFFUSEDIRECTUV = 0;
  38944. _this.AMBIENT = false;
  38945. _this.AMBIENTDIRECTUV = 0;
  38946. _this.OPACITY = false;
  38947. _this.OPACITYDIRECTUV = 0;
  38948. _this.OPACITYRGB = false;
  38949. _this.REFLECTION = false;
  38950. _this.EMISSIVE = false;
  38951. _this.EMISSIVEDIRECTUV = 0;
  38952. _this.SPECULAR = false;
  38953. _this.SPECULARDIRECTUV = 0;
  38954. _this.BUMP = false;
  38955. _this.BUMPDIRECTUV = 0;
  38956. _this.PARALLAX = false;
  38957. _this.PARALLAXOCCLUSION = false;
  38958. _this.SPECULAROVERALPHA = false;
  38959. _this.CLIPPLANE = false;
  38960. _this.ALPHATEST = false;
  38961. _this.DEPTHPREPASS = false;
  38962. _this.ALPHAFROMDIFFUSE = false;
  38963. _this.POINTSIZE = false;
  38964. _this.FOG = false;
  38965. _this.SPECULARTERM = false;
  38966. _this.DIFFUSEFRESNEL = false;
  38967. _this.OPACITYFRESNEL = false;
  38968. _this.REFLECTIONFRESNEL = false;
  38969. _this.REFRACTIONFRESNEL = false;
  38970. _this.EMISSIVEFRESNEL = false;
  38971. _this.FRESNEL = false;
  38972. _this.NORMAL = false;
  38973. _this.UV1 = false;
  38974. _this.UV2 = false;
  38975. _this.VERTEXCOLOR = false;
  38976. _this.VERTEXALPHA = false;
  38977. _this.NUM_BONE_INFLUENCERS = 0;
  38978. _this.BonesPerMesh = 0;
  38979. _this.INSTANCES = false;
  38980. _this.GLOSSINESS = false;
  38981. _this.ROUGHNESS = false;
  38982. _this.EMISSIVEASILLUMINATION = false;
  38983. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38984. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38985. _this.LIGHTMAP = false;
  38986. _this.LIGHTMAPDIRECTUV = 0;
  38987. _this.OBJECTSPACE_NORMALMAP = false;
  38988. _this.USELIGHTMAPASSHADOWMAP = false;
  38989. _this.REFLECTIONMAP_3D = false;
  38990. _this.REFLECTIONMAP_SPHERICAL = false;
  38991. _this.REFLECTIONMAP_PLANAR = false;
  38992. _this.REFLECTIONMAP_CUBIC = false;
  38993. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38994. _this.REFLECTIONMAP_PROJECTION = false;
  38995. _this.REFLECTIONMAP_SKYBOX = false;
  38996. _this.REFLECTIONMAP_EXPLICIT = false;
  38997. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38998. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38999. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39000. _this.INVERTCUBICMAP = false;
  39001. _this.LOGARITHMICDEPTH = false;
  39002. _this.REFRACTION = false;
  39003. _this.REFRACTIONMAP_3D = false;
  39004. _this.REFLECTIONOVERALPHA = false;
  39005. _this.TWOSIDEDLIGHTING = false;
  39006. _this.SHADOWFLOAT = false;
  39007. _this.MORPHTARGETS = false;
  39008. _this.MORPHTARGETS_NORMAL = false;
  39009. _this.MORPHTARGETS_TANGENT = false;
  39010. _this.NUM_MORPH_INFLUENCERS = 0;
  39011. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39012. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39013. _this.IMAGEPROCESSING = false;
  39014. _this.VIGNETTE = false;
  39015. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39016. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39017. _this.TONEMAPPING = false;
  39018. _this.CONTRAST = false;
  39019. _this.COLORCURVES = false;
  39020. _this.COLORGRADING = false;
  39021. _this.COLORGRADING3D = false;
  39022. _this.SAMPLER3DGREENDEPTH = false;
  39023. _this.SAMPLER3DBGRMAP = false;
  39024. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39025. _this.EXPOSURE = false;
  39026. _this.GRAIN = false;
  39027. _this.rebuild();
  39028. return _this;
  39029. }
  39030. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39031. var modes = [
  39032. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39033. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39034. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39035. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39036. ];
  39037. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39038. var mode = modes_1[_i];
  39039. this[mode] = (mode === modeToEnable);
  39040. }
  39041. };
  39042. return StandardMaterialDefines;
  39043. }(BABYLON.MaterialDefines));
  39044. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39045. var StandardMaterial = /** @class */ (function (_super) {
  39046. __extends(StandardMaterial, _super);
  39047. function StandardMaterial(name, scene) {
  39048. var _this = _super.call(this, name, scene) || this;
  39049. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39050. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39051. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39052. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39053. _this.specularPower = 64;
  39054. _this._useAlphaFromDiffuseTexture = false;
  39055. _this._useEmissiveAsIllumination = false;
  39056. _this._linkEmissiveWithDiffuse = false;
  39057. _this._useSpecularOverAlpha = false;
  39058. _this._useReflectionOverAlpha = false;
  39059. _this._disableLighting = false;
  39060. _this._useObjectSpaceNormalMap = false;
  39061. _this._useParallax = false;
  39062. _this._useParallaxOcclusion = false;
  39063. _this.parallaxScaleBias = 0.05;
  39064. _this._roughness = 0;
  39065. _this.indexOfRefraction = 0.98;
  39066. _this.invertRefractionY = true;
  39067. _this._useLightmapAsShadowmap = false;
  39068. _this._useReflectionFresnelFromSpecular = false;
  39069. _this._useGlossinessFromSpecularMapAlpha = false;
  39070. _this._maxSimultaneousLights = 4;
  39071. /**
  39072. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39073. */
  39074. _this._invertNormalMapX = false;
  39075. /**
  39076. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39077. */
  39078. _this._invertNormalMapY = false;
  39079. /**
  39080. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39081. */
  39082. _this._twoSidedLighting = false;
  39083. _this._renderTargets = new BABYLON.SmartArray(16);
  39084. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39085. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39086. // Setup the default processing configuration to the scene.
  39087. _this._attachImageProcessingConfiguration(null);
  39088. _this.getRenderTargetTextures = function () {
  39089. _this._renderTargets.reset();
  39090. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39091. _this._renderTargets.push(_this._reflectionTexture);
  39092. }
  39093. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39094. _this._renderTargets.push(_this._refractionTexture);
  39095. }
  39096. return _this._renderTargets;
  39097. };
  39098. return _this;
  39099. }
  39100. ;
  39101. ;
  39102. ;
  39103. ;
  39104. ;
  39105. ;
  39106. ;
  39107. ;
  39108. ;
  39109. ;
  39110. ;
  39111. ;
  39112. ;
  39113. ;
  39114. ;
  39115. ;
  39116. ;
  39117. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39118. /**
  39119. * Gets the image processing configuration used either in this material.
  39120. */
  39121. get: function () {
  39122. return this._imageProcessingConfiguration;
  39123. },
  39124. /**
  39125. * Sets the Default image processing configuration used either in the this material.
  39126. *
  39127. * If sets to null, the scene one is in use.
  39128. */
  39129. set: function (value) {
  39130. this._attachImageProcessingConfiguration(value);
  39131. // Ensure the effect will be rebuilt.
  39132. this._markAllSubMeshesAsTexturesDirty();
  39133. },
  39134. enumerable: true,
  39135. configurable: true
  39136. });
  39137. /**
  39138. * Attaches a new image processing configuration to the Standard Material.
  39139. * @param configuration
  39140. */
  39141. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39142. var _this = this;
  39143. if (configuration === this._imageProcessingConfiguration) {
  39144. return;
  39145. }
  39146. // Detaches observer.
  39147. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39148. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39149. }
  39150. // Pick the scene configuration if needed.
  39151. if (!configuration) {
  39152. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39153. }
  39154. else {
  39155. this._imageProcessingConfiguration = configuration;
  39156. }
  39157. // Attaches observer.
  39158. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39159. _this._markAllSubMeshesAsImageProcessingDirty();
  39160. });
  39161. };
  39162. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39163. /**
  39164. * Gets wether the color curves effect is enabled.
  39165. */
  39166. get: function () {
  39167. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39168. },
  39169. /**
  39170. * Sets wether the color curves effect is enabled.
  39171. */
  39172. set: function (value) {
  39173. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39174. },
  39175. enumerable: true,
  39176. configurable: true
  39177. });
  39178. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39179. /**
  39180. * Gets wether the color grading effect is enabled.
  39181. */
  39182. get: function () {
  39183. return this.imageProcessingConfiguration.colorGradingEnabled;
  39184. },
  39185. /**
  39186. * Gets wether the color grading effect is enabled.
  39187. */
  39188. set: function (value) {
  39189. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39190. },
  39191. enumerable: true,
  39192. configurable: true
  39193. });
  39194. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39195. /**
  39196. * Gets wether tonemapping is enabled or not.
  39197. */
  39198. get: function () {
  39199. return this._imageProcessingConfiguration.toneMappingEnabled;
  39200. },
  39201. /**
  39202. * Sets wether tonemapping is enabled or not
  39203. */
  39204. set: function (value) {
  39205. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39206. },
  39207. enumerable: true,
  39208. configurable: true
  39209. });
  39210. ;
  39211. ;
  39212. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39213. /**
  39214. * The camera exposure used on this material.
  39215. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39216. * This corresponds to a photographic exposure.
  39217. */
  39218. get: function () {
  39219. return this._imageProcessingConfiguration.exposure;
  39220. },
  39221. /**
  39222. * The camera exposure used on this material.
  39223. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39224. * This corresponds to a photographic exposure.
  39225. */
  39226. set: function (value) {
  39227. this._imageProcessingConfiguration.exposure = value;
  39228. },
  39229. enumerable: true,
  39230. configurable: true
  39231. });
  39232. ;
  39233. ;
  39234. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39235. /**
  39236. * Gets The camera contrast used on this material.
  39237. */
  39238. get: function () {
  39239. return this._imageProcessingConfiguration.contrast;
  39240. },
  39241. /**
  39242. * Sets The camera contrast used on this material.
  39243. */
  39244. set: function (value) {
  39245. this._imageProcessingConfiguration.contrast = value;
  39246. },
  39247. enumerable: true,
  39248. configurable: true
  39249. });
  39250. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39251. /**
  39252. * Gets the Color Grading 2D Lookup Texture.
  39253. */
  39254. get: function () {
  39255. return this._imageProcessingConfiguration.colorGradingTexture;
  39256. },
  39257. /**
  39258. * Sets the Color Grading 2D Lookup Texture.
  39259. */
  39260. set: function (value) {
  39261. this._imageProcessingConfiguration.colorGradingTexture = value;
  39262. },
  39263. enumerable: true,
  39264. configurable: true
  39265. });
  39266. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39267. /**
  39268. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39269. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39270. * 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;
  39271. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39272. */
  39273. get: function () {
  39274. return this._imageProcessingConfiguration.colorCurves;
  39275. },
  39276. /**
  39277. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39278. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39279. * 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;
  39280. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39281. */
  39282. set: function (value) {
  39283. this._imageProcessingConfiguration.colorCurves = value;
  39284. },
  39285. enumerable: true,
  39286. configurable: true
  39287. });
  39288. StandardMaterial.prototype.getClassName = function () {
  39289. return "StandardMaterial";
  39290. };
  39291. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39292. get: function () {
  39293. return this._useLogarithmicDepth;
  39294. },
  39295. set: function (value) {
  39296. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39297. this._markAllSubMeshesAsMiscDirty();
  39298. },
  39299. enumerable: true,
  39300. configurable: true
  39301. });
  39302. StandardMaterial.prototype.needAlphaBlending = function () {
  39303. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39304. };
  39305. StandardMaterial.prototype.needAlphaTesting = function () {
  39306. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39307. };
  39308. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39309. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39310. };
  39311. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39312. return this._diffuseTexture;
  39313. };
  39314. /**
  39315. * Child classes can use it to update shaders
  39316. */
  39317. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39318. if (useInstances === void 0) { useInstances = false; }
  39319. if (subMesh.effect && this.isFrozen) {
  39320. if (this._wasPreviouslyReady && subMesh.effect) {
  39321. return true;
  39322. }
  39323. }
  39324. if (!subMesh._materialDefines) {
  39325. subMesh._materialDefines = new StandardMaterialDefines();
  39326. }
  39327. var scene = this.getScene();
  39328. var defines = subMesh._materialDefines;
  39329. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39330. if (defines._renderId === scene.getRenderId()) {
  39331. return true;
  39332. }
  39333. }
  39334. var engine = scene.getEngine();
  39335. // Lights
  39336. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39337. // Textures
  39338. if (defines._areTexturesDirty) {
  39339. defines._needUVs = false;
  39340. defines.MAINUV1 = false;
  39341. defines.MAINUV2 = false;
  39342. if (scene.texturesEnabled) {
  39343. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39344. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39345. return false;
  39346. }
  39347. else {
  39348. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39349. }
  39350. }
  39351. else {
  39352. defines.DIFFUSE = false;
  39353. }
  39354. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39355. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39356. return false;
  39357. }
  39358. else {
  39359. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39360. }
  39361. }
  39362. else {
  39363. defines.AMBIENT = false;
  39364. }
  39365. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39366. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39367. return false;
  39368. }
  39369. else {
  39370. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39371. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39372. }
  39373. }
  39374. else {
  39375. defines.OPACITY = false;
  39376. }
  39377. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39378. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39379. return false;
  39380. }
  39381. else {
  39382. defines._needNormals = true;
  39383. defines.REFLECTION = true;
  39384. defines.ROUGHNESS = (this._roughness > 0);
  39385. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39386. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39387. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39388. switch (this._reflectionTexture.coordinatesMode) {
  39389. case BABYLON.Texture.CUBIC_MODE:
  39390. case BABYLON.Texture.INVCUBIC_MODE:
  39391. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39392. break;
  39393. case BABYLON.Texture.EXPLICIT_MODE:
  39394. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39395. break;
  39396. case BABYLON.Texture.PLANAR_MODE:
  39397. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39398. break;
  39399. case BABYLON.Texture.PROJECTION_MODE:
  39400. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39401. break;
  39402. case BABYLON.Texture.SKYBOX_MODE:
  39403. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39404. break;
  39405. case BABYLON.Texture.SPHERICAL_MODE:
  39406. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39407. break;
  39408. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39409. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39410. break;
  39411. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39412. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39413. break;
  39414. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39415. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39416. break;
  39417. }
  39418. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39419. }
  39420. }
  39421. else {
  39422. defines.REFLECTION = false;
  39423. }
  39424. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39425. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39426. return false;
  39427. }
  39428. else {
  39429. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39430. }
  39431. }
  39432. else {
  39433. defines.EMISSIVE = false;
  39434. }
  39435. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39436. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39437. return false;
  39438. }
  39439. else {
  39440. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39441. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39442. }
  39443. }
  39444. else {
  39445. defines.LIGHTMAP = false;
  39446. }
  39447. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39448. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39449. return false;
  39450. }
  39451. else {
  39452. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39453. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39454. }
  39455. }
  39456. else {
  39457. defines.SPECULAR = false;
  39458. }
  39459. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39460. // Bump texure can not be not blocking.
  39461. if (!this._bumpTexture.isReady()) {
  39462. return false;
  39463. }
  39464. else {
  39465. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39466. defines.PARALLAX = this._useParallax;
  39467. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39468. }
  39469. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39470. }
  39471. else {
  39472. defines.BUMP = false;
  39473. }
  39474. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39475. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39476. return false;
  39477. }
  39478. else {
  39479. defines._needUVs = true;
  39480. defines.REFRACTION = true;
  39481. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39482. }
  39483. }
  39484. else {
  39485. defines.REFRACTION = false;
  39486. }
  39487. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39488. }
  39489. else {
  39490. defines.DIFFUSE = false;
  39491. defines.AMBIENT = false;
  39492. defines.OPACITY = false;
  39493. defines.REFLECTION = false;
  39494. defines.EMISSIVE = false;
  39495. defines.LIGHTMAP = false;
  39496. defines.BUMP = false;
  39497. defines.REFRACTION = false;
  39498. }
  39499. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39500. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39501. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39502. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39503. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39504. }
  39505. if (defines._areImageProcessingDirty) {
  39506. if (!this._imageProcessingConfiguration.isReady()) {
  39507. return false;
  39508. }
  39509. this._imageProcessingConfiguration.prepareDefines(defines);
  39510. }
  39511. if (defines._areFresnelDirty) {
  39512. if (StandardMaterial.FresnelEnabled) {
  39513. // Fresnel
  39514. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39515. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39516. this._reflectionFresnelParameters) {
  39517. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39518. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39519. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39520. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39521. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39522. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39523. defines._needNormals = true;
  39524. defines.FRESNEL = true;
  39525. }
  39526. }
  39527. else {
  39528. defines.FRESNEL = false;
  39529. }
  39530. }
  39531. // Misc.
  39532. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39533. // Attribs
  39534. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39535. // Values that need to be evaluated on every frame
  39536. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39537. // Get correct effect
  39538. if (defines.isDirty) {
  39539. defines.markAsProcessed();
  39540. scene.resetCachedMaterial();
  39541. // Fallbacks
  39542. var fallbacks = new BABYLON.EffectFallbacks();
  39543. if (defines.REFLECTION) {
  39544. fallbacks.addFallback(0, "REFLECTION");
  39545. }
  39546. if (defines.SPECULAR) {
  39547. fallbacks.addFallback(0, "SPECULAR");
  39548. }
  39549. if (defines.BUMP) {
  39550. fallbacks.addFallback(0, "BUMP");
  39551. }
  39552. if (defines.PARALLAX) {
  39553. fallbacks.addFallback(1, "PARALLAX");
  39554. }
  39555. if (defines.PARALLAXOCCLUSION) {
  39556. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39557. }
  39558. if (defines.SPECULAROVERALPHA) {
  39559. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39560. }
  39561. if (defines.FOG) {
  39562. fallbacks.addFallback(1, "FOG");
  39563. }
  39564. if (defines.POINTSIZE) {
  39565. fallbacks.addFallback(0, "POINTSIZE");
  39566. }
  39567. if (defines.LOGARITHMICDEPTH) {
  39568. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39569. }
  39570. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39571. if (defines.SPECULARTERM) {
  39572. fallbacks.addFallback(0, "SPECULARTERM");
  39573. }
  39574. if (defines.DIFFUSEFRESNEL) {
  39575. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39576. }
  39577. if (defines.OPACITYFRESNEL) {
  39578. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39579. }
  39580. if (defines.REFLECTIONFRESNEL) {
  39581. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39582. }
  39583. if (defines.EMISSIVEFRESNEL) {
  39584. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39585. }
  39586. if (defines.FRESNEL) {
  39587. fallbacks.addFallback(4, "FRESNEL");
  39588. }
  39589. //Attributes
  39590. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39591. if (defines.NORMAL) {
  39592. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39593. }
  39594. if (defines.UV1) {
  39595. attribs.push(BABYLON.VertexBuffer.UVKind);
  39596. }
  39597. if (defines.UV2) {
  39598. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39599. }
  39600. if (defines.VERTEXCOLOR) {
  39601. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39602. }
  39603. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39604. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39605. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39606. var shaderName = "default";
  39607. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39608. "vFogInfos", "vFogColor", "pointSize",
  39609. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39610. "mBones",
  39611. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39612. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39613. "vReflectionPosition", "vReflectionSize",
  39614. "logarithmicDepthConstant", "vTangentSpaceParams"
  39615. ];
  39616. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39617. var uniformBuffers = ["Material", "Scene"];
  39618. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39619. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39620. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39621. uniformsNames: uniforms,
  39622. uniformBuffersNames: uniformBuffers,
  39623. samplers: samplers,
  39624. defines: defines,
  39625. maxSimultaneousLights: this._maxSimultaneousLights
  39626. });
  39627. if (this.customShaderNameResolve) {
  39628. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39629. }
  39630. var join = defines.toString();
  39631. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39632. attributes: attribs,
  39633. uniformsNames: uniforms,
  39634. uniformBuffersNames: uniformBuffers,
  39635. samplers: samplers,
  39636. defines: join,
  39637. fallbacks: fallbacks,
  39638. onCompiled: this.onCompiled,
  39639. onError: this.onError,
  39640. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39641. }, engine), defines);
  39642. this.buildUniformLayout();
  39643. }
  39644. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39645. return false;
  39646. }
  39647. defines._renderId = scene.getRenderId();
  39648. this._wasPreviouslyReady = true;
  39649. return true;
  39650. };
  39651. StandardMaterial.prototype.buildUniformLayout = function () {
  39652. // Order is important !
  39653. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39654. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39655. this._uniformBuffer.addUniform("opacityParts", 4);
  39656. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39657. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39658. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39659. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39660. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39661. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39662. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39663. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39664. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39665. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39666. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39667. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39668. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39669. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39670. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39671. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39672. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39673. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39674. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39675. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39676. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39677. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39678. this._uniformBuffer.addUniform("specularMatrix", 16);
  39679. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39680. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39681. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39682. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39683. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39684. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39685. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39686. this._uniformBuffer.addUniform("pointSize", 1);
  39687. this._uniformBuffer.create();
  39688. };
  39689. StandardMaterial.prototype.unbind = function () {
  39690. if (this._activeEffect) {
  39691. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39692. this._activeEffect.setTexture("reflection2DSampler", null);
  39693. }
  39694. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39695. this._activeEffect.setTexture("refraction2DSampler", null);
  39696. }
  39697. }
  39698. _super.prototype.unbind.call(this);
  39699. };
  39700. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39701. var scene = this.getScene();
  39702. var defines = subMesh._materialDefines;
  39703. if (!defines) {
  39704. return;
  39705. }
  39706. var effect = subMesh.effect;
  39707. if (!effect) {
  39708. return;
  39709. }
  39710. this._activeEffect = effect;
  39711. // Matrices
  39712. this.bindOnlyWorldMatrix(world);
  39713. // Normal Matrix
  39714. if (defines.OBJECTSPACE_NORMALMAP) {
  39715. world.toNormalMatrix(this._normalMatrix);
  39716. this.bindOnlyNormalMatrix(this._normalMatrix);
  39717. }
  39718. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39719. // Bones
  39720. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39721. if (mustRebind) {
  39722. this._uniformBuffer.bindToEffect(effect, "Material");
  39723. this.bindViewProjection(effect);
  39724. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39725. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39726. // Fresnel
  39727. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39728. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39729. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39730. }
  39731. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39732. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39733. }
  39734. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39735. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39736. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39737. }
  39738. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39739. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39740. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39741. }
  39742. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39743. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39744. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39745. }
  39746. }
  39747. // Textures
  39748. if (scene.texturesEnabled) {
  39749. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39750. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39751. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39752. }
  39753. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39754. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39755. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39756. }
  39757. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39758. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39759. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39760. }
  39761. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39762. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39763. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39764. if (this._reflectionTexture.boundingBoxSize) {
  39765. var cubeTexture = this._reflectionTexture;
  39766. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39767. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39768. }
  39769. }
  39770. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39771. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39772. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39773. }
  39774. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39775. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39776. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39777. }
  39778. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39779. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39780. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39781. }
  39782. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39783. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39784. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39785. if (scene._mirroredCameraPosition) {
  39786. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39787. }
  39788. else {
  39789. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39790. }
  39791. }
  39792. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39793. var depth = 1.0;
  39794. if (!this._refractionTexture.isCube) {
  39795. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39796. if (this._refractionTexture.depth) {
  39797. depth = this._refractionTexture.depth;
  39798. }
  39799. }
  39800. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39801. }
  39802. }
  39803. // Point size
  39804. if (this.pointsCloud) {
  39805. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39806. }
  39807. if (defines.SPECULARTERM) {
  39808. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39809. }
  39810. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39811. // Diffuse
  39812. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39813. }
  39814. // Textures
  39815. if (scene.texturesEnabled) {
  39816. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39817. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39818. }
  39819. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39820. effect.setTexture("ambientSampler", this._ambientTexture);
  39821. }
  39822. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39823. effect.setTexture("opacitySampler", this._opacityTexture);
  39824. }
  39825. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39826. if (this._reflectionTexture.isCube) {
  39827. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39828. }
  39829. else {
  39830. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39831. }
  39832. }
  39833. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39834. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39835. }
  39836. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39837. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39838. }
  39839. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39840. effect.setTexture("specularSampler", this._specularTexture);
  39841. }
  39842. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39843. effect.setTexture("bumpSampler", this._bumpTexture);
  39844. }
  39845. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39846. var depth = 1.0;
  39847. if (this._refractionTexture.isCube) {
  39848. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39849. }
  39850. else {
  39851. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39852. }
  39853. }
  39854. }
  39855. // Clip plane
  39856. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39857. // Colors
  39858. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39859. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39860. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39861. }
  39862. if (mustRebind || !this.isFrozen) {
  39863. // Lights
  39864. if (scene.lightsEnabled && !this._disableLighting) {
  39865. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39866. }
  39867. // View
  39868. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39869. this.bindView(effect);
  39870. }
  39871. // Fog
  39872. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39873. // Morph targets
  39874. if (defines.NUM_MORPH_INFLUENCERS) {
  39875. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39876. }
  39877. // Log. depth
  39878. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39879. // image processing
  39880. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39881. this._imageProcessingConfiguration.bind(this._activeEffect);
  39882. }
  39883. }
  39884. this._uniformBuffer.update();
  39885. this._afterBind(mesh, this._activeEffect);
  39886. };
  39887. StandardMaterial.prototype.getAnimatables = function () {
  39888. var results = [];
  39889. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39890. results.push(this._diffuseTexture);
  39891. }
  39892. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39893. results.push(this._ambientTexture);
  39894. }
  39895. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39896. results.push(this._opacityTexture);
  39897. }
  39898. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39899. results.push(this._reflectionTexture);
  39900. }
  39901. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39902. results.push(this._emissiveTexture);
  39903. }
  39904. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39905. results.push(this._specularTexture);
  39906. }
  39907. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39908. results.push(this._bumpTexture);
  39909. }
  39910. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39911. results.push(this._lightmapTexture);
  39912. }
  39913. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39914. results.push(this._refractionTexture);
  39915. }
  39916. return results;
  39917. };
  39918. StandardMaterial.prototype.getActiveTextures = function () {
  39919. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39920. if (this._diffuseTexture) {
  39921. activeTextures.push(this._diffuseTexture);
  39922. }
  39923. if (this._ambientTexture) {
  39924. activeTextures.push(this._ambientTexture);
  39925. }
  39926. if (this._opacityTexture) {
  39927. activeTextures.push(this._opacityTexture);
  39928. }
  39929. if (this._reflectionTexture) {
  39930. activeTextures.push(this._reflectionTexture);
  39931. }
  39932. if (this._emissiveTexture) {
  39933. activeTextures.push(this._emissiveTexture);
  39934. }
  39935. if (this._specularTexture) {
  39936. activeTextures.push(this._specularTexture);
  39937. }
  39938. if (this._bumpTexture) {
  39939. activeTextures.push(this._bumpTexture);
  39940. }
  39941. if (this._lightmapTexture) {
  39942. activeTextures.push(this._lightmapTexture);
  39943. }
  39944. if (this._refractionTexture) {
  39945. activeTextures.push(this._refractionTexture);
  39946. }
  39947. return activeTextures;
  39948. };
  39949. StandardMaterial.prototype.hasTexture = function (texture) {
  39950. if (_super.prototype.hasTexture.call(this, texture)) {
  39951. return true;
  39952. }
  39953. if (this._diffuseTexture === texture) {
  39954. return true;
  39955. }
  39956. if (this._ambientTexture === texture) {
  39957. return true;
  39958. }
  39959. if (this._opacityTexture === texture) {
  39960. return true;
  39961. }
  39962. if (this._reflectionTexture === texture) {
  39963. return true;
  39964. }
  39965. if (this._emissiveTexture === texture) {
  39966. return true;
  39967. }
  39968. if (this._specularTexture === texture) {
  39969. return true;
  39970. }
  39971. if (this._bumpTexture === texture) {
  39972. return true;
  39973. }
  39974. if (this._lightmapTexture === texture) {
  39975. return true;
  39976. }
  39977. if (this._refractionTexture === texture) {
  39978. return true;
  39979. }
  39980. return false;
  39981. };
  39982. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39983. if (forceDisposeTextures) {
  39984. if (this._diffuseTexture) {
  39985. this._diffuseTexture.dispose();
  39986. }
  39987. if (this._ambientTexture) {
  39988. this._ambientTexture.dispose();
  39989. }
  39990. if (this._opacityTexture) {
  39991. this._opacityTexture.dispose();
  39992. }
  39993. if (this._reflectionTexture) {
  39994. this._reflectionTexture.dispose();
  39995. }
  39996. if (this._emissiveTexture) {
  39997. this._emissiveTexture.dispose();
  39998. }
  39999. if (this._specularTexture) {
  40000. this._specularTexture.dispose();
  40001. }
  40002. if (this._bumpTexture) {
  40003. this._bumpTexture.dispose();
  40004. }
  40005. if (this._lightmapTexture) {
  40006. this._lightmapTexture.dispose();
  40007. }
  40008. if (this._refractionTexture) {
  40009. this._refractionTexture.dispose();
  40010. }
  40011. }
  40012. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40013. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40014. }
  40015. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40016. };
  40017. StandardMaterial.prototype.clone = function (name) {
  40018. var _this = this;
  40019. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40020. result.name = name;
  40021. result.id = name;
  40022. return result;
  40023. };
  40024. StandardMaterial.prototype.serialize = function () {
  40025. return BABYLON.SerializationHelper.Serialize(this);
  40026. };
  40027. // Statics
  40028. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40029. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40030. };
  40031. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40032. get: function () {
  40033. return StandardMaterial._DiffuseTextureEnabled;
  40034. },
  40035. set: function (value) {
  40036. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40037. return;
  40038. }
  40039. StandardMaterial._DiffuseTextureEnabled = value;
  40040. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40041. },
  40042. enumerable: true,
  40043. configurable: true
  40044. });
  40045. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40046. get: function () {
  40047. return StandardMaterial._AmbientTextureEnabled;
  40048. },
  40049. set: function (value) {
  40050. if (StandardMaterial._AmbientTextureEnabled === value) {
  40051. return;
  40052. }
  40053. StandardMaterial._AmbientTextureEnabled = value;
  40054. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40055. },
  40056. enumerable: true,
  40057. configurable: true
  40058. });
  40059. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40060. get: function () {
  40061. return StandardMaterial._OpacityTextureEnabled;
  40062. },
  40063. set: function (value) {
  40064. if (StandardMaterial._OpacityTextureEnabled === value) {
  40065. return;
  40066. }
  40067. StandardMaterial._OpacityTextureEnabled = value;
  40068. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40069. },
  40070. enumerable: true,
  40071. configurable: true
  40072. });
  40073. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40074. get: function () {
  40075. return StandardMaterial._ReflectionTextureEnabled;
  40076. },
  40077. set: function (value) {
  40078. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40079. return;
  40080. }
  40081. StandardMaterial._ReflectionTextureEnabled = value;
  40082. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40083. },
  40084. enumerable: true,
  40085. configurable: true
  40086. });
  40087. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40088. get: function () {
  40089. return StandardMaterial._EmissiveTextureEnabled;
  40090. },
  40091. set: function (value) {
  40092. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40093. return;
  40094. }
  40095. StandardMaterial._EmissiveTextureEnabled = value;
  40096. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40097. },
  40098. enumerable: true,
  40099. configurable: true
  40100. });
  40101. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40102. get: function () {
  40103. return StandardMaterial._SpecularTextureEnabled;
  40104. },
  40105. set: function (value) {
  40106. if (StandardMaterial._SpecularTextureEnabled === value) {
  40107. return;
  40108. }
  40109. StandardMaterial._SpecularTextureEnabled = value;
  40110. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40111. },
  40112. enumerable: true,
  40113. configurable: true
  40114. });
  40115. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40116. get: function () {
  40117. return StandardMaterial._BumpTextureEnabled;
  40118. },
  40119. set: function (value) {
  40120. if (StandardMaterial._BumpTextureEnabled === value) {
  40121. return;
  40122. }
  40123. StandardMaterial._BumpTextureEnabled = value;
  40124. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40125. },
  40126. enumerable: true,
  40127. configurable: true
  40128. });
  40129. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40130. get: function () {
  40131. return StandardMaterial._LightmapTextureEnabled;
  40132. },
  40133. set: function (value) {
  40134. if (StandardMaterial._LightmapTextureEnabled === value) {
  40135. return;
  40136. }
  40137. StandardMaterial._LightmapTextureEnabled = value;
  40138. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40144. get: function () {
  40145. return StandardMaterial._RefractionTextureEnabled;
  40146. },
  40147. set: function (value) {
  40148. if (StandardMaterial._RefractionTextureEnabled === value) {
  40149. return;
  40150. }
  40151. StandardMaterial._RefractionTextureEnabled = value;
  40152. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40153. },
  40154. enumerable: true,
  40155. configurable: true
  40156. });
  40157. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40158. get: function () {
  40159. return StandardMaterial._ColorGradingTextureEnabled;
  40160. },
  40161. set: function (value) {
  40162. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40163. return;
  40164. }
  40165. StandardMaterial._ColorGradingTextureEnabled = value;
  40166. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40167. },
  40168. enumerable: true,
  40169. configurable: true
  40170. });
  40171. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40172. get: function () {
  40173. return StandardMaterial._FresnelEnabled;
  40174. },
  40175. set: function (value) {
  40176. if (StandardMaterial._FresnelEnabled === value) {
  40177. return;
  40178. }
  40179. StandardMaterial._FresnelEnabled = value;
  40180. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40181. },
  40182. enumerable: true,
  40183. configurable: true
  40184. });
  40185. // Flags used to enable or disable a type of texture for all Standard Materials
  40186. StandardMaterial._DiffuseTextureEnabled = true;
  40187. StandardMaterial._AmbientTextureEnabled = true;
  40188. StandardMaterial._OpacityTextureEnabled = true;
  40189. StandardMaterial._ReflectionTextureEnabled = true;
  40190. StandardMaterial._EmissiveTextureEnabled = true;
  40191. StandardMaterial._SpecularTextureEnabled = true;
  40192. StandardMaterial._BumpTextureEnabled = true;
  40193. StandardMaterial._LightmapTextureEnabled = true;
  40194. StandardMaterial._RefractionTextureEnabled = true;
  40195. StandardMaterial._ColorGradingTextureEnabled = true;
  40196. StandardMaterial._FresnelEnabled = true;
  40197. __decorate([
  40198. BABYLON.serializeAsTexture("diffuseTexture")
  40199. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40200. __decorate([
  40201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40202. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40203. __decorate([
  40204. BABYLON.serializeAsTexture("ambientTexture")
  40205. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40206. __decorate([
  40207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40208. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40209. __decorate([
  40210. BABYLON.serializeAsTexture("opacityTexture")
  40211. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40212. __decorate([
  40213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40214. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40215. __decorate([
  40216. BABYLON.serializeAsTexture("reflectionTexture")
  40217. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40218. __decorate([
  40219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40220. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40221. __decorate([
  40222. BABYLON.serializeAsTexture("emissiveTexture")
  40223. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40224. __decorate([
  40225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40226. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40227. __decorate([
  40228. BABYLON.serializeAsTexture("specularTexture")
  40229. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40230. __decorate([
  40231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40232. ], StandardMaterial.prototype, "specularTexture", void 0);
  40233. __decorate([
  40234. BABYLON.serializeAsTexture("bumpTexture")
  40235. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40236. __decorate([
  40237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40238. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40239. __decorate([
  40240. BABYLON.serializeAsTexture("lightmapTexture")
  40241. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40242. __decorate([
  40243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40244. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40245. __decorate([
  40246. BABYLON.serializeAsTexture("refractionTexture")
  40247. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40248. __decorate([
  40249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40250. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40251. __decorate([
  40252. BABYLON.serializeAsColor3("ambient")
  40253. ], StandardMaterial.prototype, "ambientColor", void 0);
  40254. __decorate([
  40255. BABYLON.serializeAsColor3("diffuse")
  40256. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40257. __decorate([
  40258. BABYLON.serializeAsColor3("specular")
  40259. ], StandardMaterial.prototype, "specularColor", void 0);
  40260. __decorate([
  40261. BABYLON.serializeAsColor3("emissive")
  40262. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40263. __decorate([
  40264. BABYLON.serialize()
  40265. ], StandardMaterial.prototype, "specularPower", void 0);
  40266. __decorate([
  40267. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40268. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40269. __decorate([
  40270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40271. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40272. __decorate([
  40273. BABYLON.serialize("useEmissiveAsIllumination")
  40274. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40275. __decorate([
  40276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40277. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40278. __decorate([
  40279. BABYLON.serialize("linkEmissiveWithDiffuse")
  40280. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40281. __decorate([
  40282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40283. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40284. __decorate([
  40285. BABYLON.serialize("useSpecularOverAlpha")
  40286. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40287. __decorate([
  40288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40289. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40290. __decorate([
  40291. BABYLON.serialize("useReflectionOverAlpha")
  40292. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40293. __decorate([
  40294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40295. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40296. __decorate([
  40297. BABYLON.serialize("disableLighting")
  40298. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40299. __decorate([
  40300. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40301. ], StandardMaterial.prototype, "disableLighting", void 0);
  40302. __decorate([
  40303. BABYLON.serialize("useObjectSpaceNormalMap")
  40304. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40305. __decorate([
  40306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40307. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40308. __decorate([
  40309. BABYLON.serialize("useParallax")
  40310. ], StandardMaterial.prototype, "_useParallax", void 0);
  40311. __decorate([
  40312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40313. ], StandardMaterial.prototype, "useParallax", void 0);
  40314. __decorate([
  40315. BABYLON.serialize("useParallaxOcclusion")
  40316. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40317. __decorate([
  40318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40319. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40320. __decorate([
  40321. BABYLON.serialize()
  40322. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40323. __decorate([
  40324. BABYLON.serialize("roughness")
  40325. ], StandardMaterial.prototype, "_roughness", void 0);
  40326. __decorate([
  40327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40328. ], StandardMaterial.prototype, "roughness", void 0);
  40329. __decorate([
  40330. BABYLON.serialize()
  40331. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40332. __decorate([
  40333. BABYLON.serialize()
  40334. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40335. __decorate([
  40336. BABYLON.serialize("useLightmapAsShadowmap")
  40337. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40338. __decorate([
  40339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40340. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40341. __decorate([
  40342. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40343. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40344. __decorate([
  40345. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40346. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40347. __decorate([
  40348. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40349. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40350. __decorate([
  40351. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40352. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40353. __decorate([
  40354. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40355. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40356. __decorate([
  40357. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40358. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40359. __decorate([
  40360. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40361. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40362. __decorate([
  40363. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40364. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40365. __decorate([
  40366. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40367. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40368. __decorate([
  40369. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40370. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40371. __decorate([
  40372. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40373. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40374. __decorate([
  40375. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40376. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40377. __decorate([
  40378. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40379. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40380. __decorate([
  40381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40382. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40383. __decorate([
  40384. BABYLON.serialize("maxSimultaneousLights")
  40385. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40386. __decorate([
  40387. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40388. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40389. __decorate([
  40390. BABYLON.serialize("invertNormalMapX")
  40391. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40392. __decorate([
  40393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40394. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40395. __decorate([
  40396. BABYLON.serialize("invertNormalMapY")
  40397. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40398. __decorate([
  40399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40400. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40401. __decorate([
  40402. BABYLON.serialize("twoSidedLighting")
  40403. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40404. __decorate([
  40405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40406. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40407. __decorate([
  40408. BABYLON.serialize()
  40409. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40410. return StandardMaterial;
  40411. }(BABYLON.PushMaterial));
  40412. BABYLON.StandardMaterial = StandardMaterial;
  40413. })(BABYLON || (BABYLON = {}));
  40414. //# sourceMappingURL=babylon.standardMaterial.js.map
  40415. var BABYLON;
  40416. (function (BABYLON) {
  40417. /**
  40418. * Manages the defines for the PBR Material.
  40419. */
  40420. var PBRMaterialDefines = /** @class */ (function (_super) {
  40421. __extends(PBRMaterialDefines, _super);
  40422. /**
  40423. * Initializes the PBR Material defines.
  40424. */
  40425. function PBRMaterialDefines() {
  40426. var _this = _super.call(this) || this;
  40427. _this.PBR = true;
  40428. _this.MAINUV1 = false;
  40429. _this.MAINUV2 = false;
  40430. _this.UV1 = false;
  40431. _this.UV2 = false;
  40432. _this.ALBEDO = false;
  40433. _this.ALBEDODIRECTUV = 0;
  40434. _this.VERTEXCOLOR = false;
  40435. _this.AMBIENT = false;
  40436. _this.AMBIENTDIRECTUV = 0;
  40437. _this.AMBIENTINGRAYSCALE = false;
  40438. _this.OPACITY = false;
  40439. _this.VERTEXALPHA = false;
  40440. _this.OPACITYDIRECTUV = 0;
  40441. _this.OPACITYRGB = false;
  40442. _this.ALPHATEST = false;
  40443. _this.DEPTHPREPASS = false;
  40444. _this.ALPHABLEND = false;
  40445. _this.ALPHAFROMALBEDO = false;
  40446. _this.ALPHATESTVALUE = 0.5;
  40447. _this.SPECULAROVERALPHA = false;
  40448. _this.RADIANCEOVERALPHA = false;
  40449. _this.ALPHAFRESNEL = false;
  40450. _this.LINEARALPHAFRESNEL = false;
  40451. _this.PREMULTIPLYALPHA = false;
  40452. _this.EMISSIVE = false;
  40453. _this.EMISSIVEDIRECTUV = 0;
  40454. _this.REFLECTIVITY = false;
  40455. _this.REFLECTIVITYDIRECTUV = 0;
  40456. _this.SPECULARTERM = false;
  40457. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40458. _this.MICROSURFACEAUTOMATIC = false;
  40459. _this.LODBASEDMICROSFURACE = false;
  40460. _this.MICROSURFACEMAP = false;
  40461. _this.MICROSURFACEMAPDIRECTUV = 0;
  40462. _this.METALLICWORKFLOW = false;
  40463. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40464. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40465. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40466. _this.AOSTOREINMETALMAPRED = false;
  40467. _this.ENVIRONMENTBRDF = false;
  40468. _this.NORMAL = false;
  40469. _this.TANGENT = false;
  40470. _this.BUMP = false;
  40471. _this.BUMPDIRECTUV = 0;
  40472. _this.OBJECTSPACE_NORMALMAP = false;
  40473. _this.PARALLAX = false;
  40474. _this.PARALLAXOCCLUSION = false;
  40475. _this.NORMALXYSCALE = true;
  40476. _this.LIGHTMAP = false;
  40477. _this.LIGHTMAPDIRECTUV = 0;
  40478. _this.USELIGHTMAPASSHADOWMAP = false;
  40479. _this.REFLECTION = false;
  40480. _this.REFLECTIONMAP_3D = false;
  40481. _this.REFLECTIONMAP_SPHERICAL = false;
  40482. _this.REFLECTIONMAP_PLANAR = false;
  40483. _this.REFLECTIONMAP_CUBIC = false;
  40484. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40485. _this.REFLECTIONMAP_PROJECTION = false;
  40486. _this.REFLECTIONMAP_SKYBOX = false;
  40487. _this.REFLECTIONMAP_EXPLICIT = false;
  40488. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40489. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40490. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40491. _this.INVERTCUBICMAP = false;
  40492. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40493. _this.USESPHERICALINVERTEX = false;
  40494. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40495. _this.LODINREFLECTIONALPHA = false;
  40496. _this.GAMMAREFLECTION = false;
  40497. _this.RADIANCEOCCLUSION = false;
  40498. _this.HORIZONOCCLUSION = false;
  40499. _this.REFRACTION = false;
  40500. _this.REFRACTIONMAP_3D = false;
  40501. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40502. _this.LODINREFRACTIONALPHA = false;
  40503. _this.GAMMAREFRACTION = false;
  40504. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40505. _this.INSTANCES = false;
  40506. _this.NUM_BONE_INFLUENCERS = 0;
  40507. _this.BonesPerMesh = 0;
  40508. _this.NONUNIFORMSCALING = false;
  40509. _this.MORPHTARGETS = false;
  40510. _this.MORPHTARGETS_NORMAL = false;
  40511. _this.MORPHTARGETS_TANGENT = false;
  40512. _this.NUM_MORPH_INFLUENCERS = 0;
  40513. _this.IMAGEPROCESSING = false;
  40514. _this.VIGNETTE = false;
  40515. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40516. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40517. _this.TONEMAPPING = false;
  40518. _this.CONTRAST = false;
  40519. _this.COLORCURVES = false;
  40520. _this.COLORGRADING = false;
  40521. _this.COLORGRADING3D = false;
  40522. _this.SAMPLER3DGREENDEPTH = false;
  40523. _this.SAMPLER3DBGRMAP = false;
  40524. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40525. _this.EXPOSURE = false;
  40526. _this.GRAIN = false;
  40527. _this.USEPHYSICALLIGHTFALLOFF = false;
  40528. _this.TWOSIDEDLIGHTING = false;
  40529. _this.SHADOWFLOAT = false;
  40530. _this.CLIPPLANE = false;
  40531. _this.POINTSIZE = false;
  40532. _this.FOG = false;
  40533. _this.LOGARITHMICDEPTH = false;
  40534. _this.FORCENORMALFORWARD = false;
  40535. _this.rebuild();
  40536. return _this;
  40537. }
  40538. /**
  40539. * Resets the PBR Material defines.
  40540. */
  40541. PBRMaterialDefines.prototype.reset = function () {
  40542. _super.prototype.reset.call(this);
  40543. this.ALPHATESTVALUE = 0.5;
  40544. this.PBR = true;
  40545. };
  40546. return PBRMaterialDefines;
  40547. }(BABYLON.MaterialDefines));
  40548. /**
  40549. * The Physically based material base class of BJS.
  40550. *
  40551. * This offers the main features of a standard PBR material.
  40552. * For more information, please refer to the documentation :
  40553. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40554. */
  40555. var PBRBaseMaterial = /** @class */ (function (_super) {
  40556. __extends(PBRBaseMaterial, _super);
  40557. /**
  40558. * Instantiates a new PBRMaterial instance.
  40559. *
  40560. * @param name The material name
  40561. * @param scene The scene the material will be use in.
  40562. */
  40563. function PBRBaseMaterial(name, scene) {
  40564. var _this = _super.call(this, name, scene) || this;
  40565. /**
  40566. * Intensity of the direct lights e.g. the four lights available in your scene.
  40567. * This impacts both the direct diffuse and specular highlights.
  40568. */
  40569. _this._directIntensity = 1.0;
  40570. /**
  40571. * Intensity of the emissive part of the material.
  40572. * This helps controlling the emissive effect without modifying the emissive color.
  40573. */
  40574. _this._emissiveIntensity = 1.0;
  40575. /**
  40576. * Intensity of the environment e.g. how much the environment will light the object
  40577. * either through harmonics for rough material or through the refelction for shiny ones.
  40578. */
  40579. _this._environmentIntensity = 1.0;
  40580. /**
  40581. * This is a special control allowing the reduction of the specular highlights coming from the
  40582. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40583. */
  40584. _this._specularIntensity = 1.0;
  40585. /**
  40586. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40587. */
  40588. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40589. /**
  40590. * Debug Control allowing disabling the bump map on this material.
  40591. */
  40592. _this._disableBumpMap = false;
  40593. /**
  40594. * AKA Occlusion Texture Intensity in other nomenclature.
  40595. */
  40596. _this._ambientTextureStrength = 1.0;
  40597. /**
  40598. * The color of a material in ambient lighting.
  40599. */
  40600. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40601. /**
  40602. * AKA Diffuse Color in other nomenclature.
  40603. */
  40604. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40605. /**
  40606. * AKA Specular Color in other nomenclature.
  40607. */
  40608. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40609. /**
  40610. * The color applied when light is reflected from a material.
  40611. */
  40612. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40613. /**
  40614. * The color applied when light is emitted from a material.
  40615. */
  40616. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40617. /**
  40618. * AKA Glossiness in other nomenclature.
  40619. */
  40620. _this._microSurface = 0.9;
  40621. /**
  40622. * source material index of refraction (IOR)' / 'destination material IOR.
  40623. */
  40624. _this._indexOfRefraction = 0.66;
  40625. /**
  40626. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40627. */
  40628. _this._invertRefractionY = false;
  40629. /**
  40630. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40631. * Materials half opaque for instance using refraction could benefit from this control.
  40632. */
  40633. _this._linkRefractionWithTransparency = false;
  40634. /**
  40635. * Specifies that the material will use the light map as a show map.
  40636. */
  40637. _this._useLightmapAsShadowmap = false;
  40638. /**
  40639. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40640. * makes the reflect vector face the model (under horizon).
  40641. */
  40642. _this._useHorizonOcclusion = true;
  40643. /**
  40644. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40645. * too much the area relying on ambient texture to define their ambient occlusion.
  40646. */
  40647. _this._useRadianceOcclusion = true;
  40648. /**
  40649. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40650. */
  40651. _this._useAlphaFromAlbedoTexture = false;
  40652. /**
  40653. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40654. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40655. */
  40656. _this._useSpecularOverAlpha = true;
  40657. /**
  40658. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40659. */
  40660. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40661. /**
  40662. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40663. */
  40664. _this._useRoughnessFromMetallicTextureAlpha = true;
  40665. /**
  40666. * Specifies if the metallic texture contains the roughness information in its green channel.
  40667. */
  40668. _this._useRoughnessFromMetallicTextureGreen = false;
  40669. /**
  40670. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40671. */
  40672. _this._useMetallnessFromMetallicTextureBlue = false;
  40673. /**
  40674. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40675. */
  40676. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40677. /**
  40678. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40679. */
  40680. _this._useAmbientInGrayScale = false;
  40681. /**
  40682. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40683. * The material will try to infer what glossiness each pixel should be.
  40684. */
  40685. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40686. /**
  40687. * BJS is using an harcoded light falloff based on a manually sets up range.
  40688. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40689. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40690. */
  40691. _this._usePhysicalLightFalloff = true;
  40692. /**
  40693. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40694. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40695. */
  40696. _this._useRadianceOverAlpha = true;
  40697. /**
  40698. * Allows using an object space normal map (instead of tangent space).
  40699. */
  40700. _this._useObjectSpaceNormalMap = false;
  40701. /**
  40702. * Allows using the bump map in parallax mode.
  40703. */
  40704. _this._useParallax = false;
  40705. /**
  40706. * Allows using the bump map in parallax occlusion mode.
  40707. */
  40708. _this._useParallaxOcclusion = false;
  40709. /**
  40710. * Controls the scale bias of the parallax mode.
  40711. */
  40712. _this._parallaxScaleBias = 0.05;
  40713. /**
  40714. * If sets to true, disables all the lights affecting the material.
  40715. */
  40716. _this._disableLighting = false;
  40717. /**
  40718. * Number of Simultaneous lights allowed on the material.
  40719. */
  40720. _this._maxSimultaneousLights = 4;
  40721. /**
  40722. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40723. */
  40724. _this._invertNormalMapX = false;
  40725. /**
  40726. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40727. */
  40728. _this._invertNormalMapY = false;
  40729. /**
  40730. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40731. */
  40732. _this._twoSidedLighting = false;
  40733. /**
  40734. * Defines the alpha limits in alpha test mode.
  40735. */
  40736. _this._alphaCutOff = 0.4;
  40737. /**
  40738. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40739. */
  40740. _this._forceAlphaTest = false;
  40741. /**
  40742. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40743. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40744. */
  40745. _this._useAlphaFresnel = false;
  40746. /**
  40747. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40748. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40749. */
  40750. _this._useLinearAlphaFresnel = false;
  40751. /**
  40752. * The transparency mode of the material.
  40753. */
  40754. _this._transparencyMode = null;
  40755. /**
  40756. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40757. * from cos thetav and roughness:
  40758. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40759. */
  40760. _this._environmentBRDFTexture = null;
  40761. /**
  40762. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40763. */
  40764. _this._forceIrradianceInFragment = false;
  40765. /**
  40766. * Force normal to face away from face.
  40767. */
  40768. _this._forceNormalForward = false;
  40769. /**
  40770. * Stores the available render targets.
  40771. */
  40772. _this._renderTargets = new BABYLON.SmartArray(16);
  40773. /**
  40774. * Sets the global ambient color for the material used in lighting calculations.
  40775. */
  40776. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40777. // Setup the default processing configuration to the scene.
  40778. _this._attachImageProcessingConfiguration(null);
  40779. _this.getRenderTargetTextures = function () {
  40780. _this._renderTargets.reset();
  40781. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40782. _this._renderTargets.push(_this._reflectionTexture);
  40783. }
  40784. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40785. _this._renderTargets.push(_this._refractionTexture);
  40786. }
  40787. return _this._renderTargets;
  40788. };
  40789. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40790. return _this;
  40791. }
  40792. /**
  40793. * Attaches a new image processing configuration to the PBR Material.
  40794. * @param configuration
  40795. */
  40796. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40797. var _this = this;
  40798. if (configuration === this._imageProcessingConfiguration) {
  40799. return;
  40800. }
  40801. // Detaches observer.
  40802. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40803. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40804. }
  40805. // Pick the scene configuration if needed.
  40806. if (!configuration) {
  40807. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40808. }
  40809. else {
  40810. this._imageProcessingConfiguration = configuration;
  40811. }
  40812. // Attaches observer.
  40813. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40814. _this._markAllSubMeshesAsImageProcessingDirty();
  40815. });
  40816. };
  40817. /**
  40818. * Gets the name of the material class.
  40819. */
  40820. PBRBaseMaterial.prototype.getClassName = function () {
  40821. return "PBRBaseMaterial";
  40822. };
  40823. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40824. /**
  40825. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40826. */
  40827. get: function () {
  40828. return this._useLogarithmicDepth;
  40829. },
  40830. /**
  40831. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40832. */
  40833. set: function (value) {
  40834. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40835. },
  40836. enumerable: true,
  40837. configurable: true
  40838. });
  40839. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40840. /**
  40841. * Gets the current transparency mode.
  40842. */
  40843. get: function () {
  40844. return this._transparencyMode;
  40845. },
  40846. /**
  40847. * Sets the transparency mode of the material.
  40848. */
  40849. set: function (value) {
  40850. if (this._transparencyMode === value) {
  40851. return;
  40852. }
  40853. this._transparencyMode = value;
  40854. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40855. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40856. },
  40857. enumerable: true,
  40858. configurable: true
  40859. });
  40860. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40861. /**
  40862. * Returns true if alpha blending should be disabled.
  40863. */
  40864. get: function () {
  40865. return (this._linkRefractionWithTransparency ||
  40866. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40867. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40868. },
  40869. enumerable: true,
  40870. configurable: true
  40871. });
  40872. /**
  40873. * Specifies whether or not this material should be rendered in alpha blend mode.
  40874. */
  40875. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40876. if (this._disableAlphaBlending) {
  40877. return false;
  40878. }
  40879. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40880. };
  40881. /**
  40882. * Specifies if the mesh will require alpha blending.
  40883. * @param mesh - BJS mesh.
  40884. */
  40885. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40886. if (this._disableAlphaBlending) {
  40887. return false;
  40888. }
  40889. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40890. };
  40891. /**
  40892. * Specifies whether or not this material should be rendered in alpha test mode.
  40893. */
  40894. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40895. if (this._forceAlphaTest) {
  40896. return true;
  40897. }
  40898. if (this._linkRefractionWithTransparency) {
  40899. return false;
  40900. }
  40901. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40902. };
  40903. /**
  40904. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40905. */
  40906. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40907. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40908. };
  40909. /**
  40910. * Gets the texture used for the alpha test.
  40911. */
  40912. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40913. return this._albedoTexture;
  40914. };
  40915. /**
  40916. * Specifies that the submesh is ready to be used.
  40917. * @param mesh - BJS mesh.
  40918. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40919. * @param useInstances - Specifies that instances should be used.
  40920. * @returns - boolean indicating that the submesh is ready or not.
  40921. */
  40922. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40923. if (subMesh.effect && this.isFrozen) {
  40924. if (this._wasPreviouslyReady) {
  40925. return true;
  40926. }
  40927. }
  40928. if (!subMesh._materialDefines) {
  40929. subMesh._materialDefines = new PBRMaterialDefines();
  40930. }
  40931. var defines = subMesh._materialDefines;
  40932. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40933. if (defines._renderId === this.getScene().getRenderId()) {
  40934. return true;
  40935. }
  40936. }
  40937. var scene = this.getScene();
  40938. var engine = scene.getEngine();
  40939. if (defines._areTexturesDirty) {
  40940. if (scene.texturesEnabled) {
  40941. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40942. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40943. return false;
  40944. }
  40945. }
  40946. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40947. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40948. return false;
  40949. }
  40950. }
  40951. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40952. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40953. return false;
  40954. }
  40955. }
  40956. var reflectionTexture = this._getReflectionTexture();
  40957. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40958. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40959. return false;
  40960. }
  40961. }
  40962. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40963. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40964. return false;
  40965. }
  40966. }
  40967. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40968. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40969. return false;
  40970. }
  40971. }
  40972. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40973. if (this._metallicTexture) {
  40974. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40975. return false;
  40976. }
  40977. }
  40978. else if (this._reflectivityTexture) {
  40979. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40980. return false;
  40981. }
  40982. }
  40983. if (this._microSurfaceTexture) {
  40984. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40985. return false;
  40986. }
  40987. }
  40988. }
  40989. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40990. // Bump texture cannot be not blocking.
  40991. if (!this._bumpTexture.isReady()) {
  40992. return false;
  40993. }
  40994. }
  40995. var refractionTexture = this._getRefractionTexture();
  40996. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40997. if (!refractionTexture.isReadyOrNotBlocking()) {
  40998. return false;
  40999. }
  41000. }
  41001. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41002. // This is blocking.
  41003. if (!this._environmentBRDFTexture.isReady()) {
  41004. return false;
  41005. }
  41006. }
  41007. }
  41008. }
  41009. if (defines._areImageProcessingDirty) {
  41010. if (!this._imageProcessingConfiguration.isReady()) {
  41011. return false;
  41012. }
  41013. }
  41014. if (!engine.getCaps().standardDerivatives) {
  41015. var bufferMesh = null;
  41016. if (mesh.getClassName() === "InstancedMesh") {
  41017. bufferMesh = mesh.sourceMesh;
  41018. }
  41019. else if (mesh.getClassName() === "Mesh") {
  41020. bufferMesh = mesh;
  41021. }
  41022. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41023. bufferMesh.createNormals(true);
  41024. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41025. }
  41026. }
  41027. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41028. if (effect) {
  41029. scene.resetCachedMaterial();
  41030. subMesh.setEffect(effect, defines);
  41031. this.buildUniformLayout();
  41032. }
  41033. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41034. return false;
  41035. }
  41036. defines._renderId = scene.getRenderId();
  41037. this._wasPreviouslyReady = true;
  41038. return true;
  41039. };
  41040. /**
  41041. * Specifies if the material uses metallic roughness workflow.
  41042. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41043. */
  41044. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41045. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41046. return true;
  41047. }
  41048. return false;
  41049. };
  41050. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41051. if (onCompiled === void 0) { onCompiled = null; }
  41052. if (onError === void 0) { onError = null; }
  41053. if (useInstances === void 0) { useInstances = null; }
  41054. if (useClipPlane === void 0) { useClipPlane = null; }
  41055. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41056. if (!defines.isDirty) {
  41057. return null;
  41058. }
  41059. defines.markAsProcessed();
  41060. var scene = this.getScene();
  41061. var engine = scene.getEngine();
  41062. // Fallbacks
  41063. var fallbacks = new BABYLON.EffectFallbacks();
  41064. var fallbackRank = 0;
  41065. if (defines.USESPHERICALINVERTEX) {
  41066. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41067. }
  41068. if (defines.FOG) {
  41069. fallbacks.addFallback(fallbackRank, "FOG");
  41070. }
  41071. if (defines.POINTSIZE) {
  41072. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41073. }
  41074. if (defines.LOGARITHMICDEPTH) {
  41075. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41076. }
  41077. if (defines.PARALLAX) {
  41078. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41079. }
  41080. if (defines.PARALLAXOCCLUSION) {
  41081. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41082. }
  41083. if (defines.ENVIRONMENTBRDF) {
  41084. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41085. }
  41086. if (defines.TANGENT) {
  41087. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41088. }
  41089. if (defines.BUMP) {
  41090. fallbacks.addFallback(fallbackRank++, "BUMP");
  41091. }
  41092. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41093. if (defines.SPECULARTERM) {
  41094. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41095. }
  41096. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41097. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41098. }
  41099. if (defines.LIGHTMAP) {
  41100. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41101. }
  41102. if (defines.NORMAL) {
  41103. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41104. }
  41105. if (defines.AMBIENT) {
  41106. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41107. }
  41108. if (defines.EMISSIVE) {
  41109. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41110. }
  41111. if (defines.VERTEXCOLOR) {
  41112. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41113. }
  41114. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41115. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41116. }
  41117. if (defines.MORPHTARGETS) {
  41118. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41119. }
  41120. //Attributes
  41121. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41122. if (defines.NORMAL) {
  41123. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41124. }
  41125. if (defines.TANGENT) {
  41126. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41127. }
  41128. if (defines.UV1) {
  41129. attribs.push(BABYLON.VertexBuffer.UVKind);
  41130. }
  41131. if (defines.UV2) {
  41132. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41133. }
  41134. if (defines.VERTEXCOLOR) {
  41135. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41136. }
  41137. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41138. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41139. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41140. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41141. "vFogInfos", "vFogColor", "pointSize",
  41142. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41143. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41144. "mBones",
  41145. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41146. "vLightingIntensity",
  41147. "logarithmicDepthConstant",
  41148. "vSphericalX", "vSphericalY", "vSphericalZ",
  41149. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41150. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41151. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41152. "vTangentSpaceParams"
  41153. ];
  41154. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41155. "bumpSampler", "lightmapSampler", "opacitySampler",
  41156. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41157. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41158. "microSurfaceSampler", "environmentBrdfSampler"];
  41159. var uniformBuffers = ["Material", "Scene"];
  41160. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41161. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41162. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41163. uniformsNames: uniforms,
  41164. uniformBuffersNames: uniformBuffers,
  41165. samplers: samplers,
  41166. defines: defines,
  41167. maxSimultaneousLights: this._maxSimultaneousLights
  41168. });
  41169. var join = defines.toString();
  41170. return engine.createEffect("pbr", {
  41171. attributes: attribs,
  41172. uniformsNames: uniforms,
  41173. uniformBuffersNames: uniformBuffers,
  41174. samplers: samplers,
  41175. defines: join,
  41176. fallbacks: fallbacks,
  41177. onCompiled: onCompiled,
  41178. onError: onError,
  41179. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41180. }, engine);
  41181. };
  41182. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41183. if (useInstances === void 0) { useInstances = null; }
  41184. if (useClipPlane === void 0) { useClipPlane = null; }
  41185. var scene = this.getScene();
  41186. var engine = scene.getEngine();
  41187. // Lights
  41188. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41189. defines._needNormals = true;
  41190. // Textures
  41191. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41192. if (defines._areTexturesDirty) {
  41193. defines._needUVs = false;
  41194. if (scene.texturesEnabled) {
  41195. if (scene.getEngine().getCaps().textureLOD) {
  41196. defines.LODBASEDMICROSFURACE = true;
  41197. }
  41198. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41200. }
  41201. else {
  41202. defines.ALBEDO = false;
  41203. }
  41204. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41205. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41206. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41207. }
  41208. else {
  41209. defines.AMBIENT = false;
  41210. }
  41211. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41212. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41213. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41214. }
  41215. else {
  41216. defines.OPACITY = false;
  41217. }
  41218. var reflectionTexture = this._getReflectionTexture();
  41219. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41220. defines.REFLECTION = true;
  41221. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41222. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41223. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41224. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41225. defines.INVERTCUBICMAP = true;
  41226. }
  41227. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41228. switch (reflectionTexture.coordinatesMode) {
  41229. case BABYLON.Texture.CUBIC_MODE:
  41230. case BABYLON.Texture.INVCUBIC_MODE:
  41231. defines.REFLECTIONMAP_CUBIC = true;
  41232. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41233. break;
  41234. case BABYLON.Texture.EXPLICIT_MODE:
  41235. defines.REFLECTIONMAP_EXPLICIT = true;
  41236. break;
  41237. case BABYLON.Texture.PLANAR_MODE:
  41238. defines.REFLECTIONMAP_PLANAR = true;
  41239. break;
  41240. case BABYLON.Texture.PROJECTION_MODE:
  41241. defines.REFLECTIONMAP_PROJECTION = true;
  41242. break;
  41243. case BABYLON.Texture.SKYBOX_MODE:
  41244. defines.REFLECTIONMAP_SKYBOX = true;
  41245. break;
  41246. case BABYLON.Texture.SPHERICAL_MODE:
  41247. defines.REFLECTIONMAP_SPHERICAL = true;
  41248. break;
  41249. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41250. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41251. break;
  41252. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41253. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41254. break;
  41255. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41256. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41257. break;
  41258. }
  41259. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41260. if (reflectionTexture.sphericalPolynomial) {
  41261. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41262. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41263. defines.USESPHERICALINVERTEX = false;
  41264. }
  41265. else {
  41266. defines.USESPHERICALINVERTEX = true;
  41267. }
  41268. }
  41269. }
  41270. }
  41271. else {
  41272. defines.REFLECTION = false;
  41273. defines.REFLECTIONMAP_3D = false;
  41274. defines.REFLECTIONMAP_SPHERICAL = false;
  41275. defines.REFLECTIONMAP_PLANAR = false;
  41276. defines.REFLECTIONMAP_CUBIC = false;
  41277. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41278. defines.REFLECTIONMAP_PROJECTION = false;
  41279. defines.REFLECTIONMAP_SKYBOX = false;
  41280. defines.REFLECTIONMAP_EXPLICIT = false;
  41281. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41282. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41283. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41284. defines.INVERTCUBICMAP = false;
  41285. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41286. defines.USESPHERICALINVERTEX = false;
  41287. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41288. defines.LODINREFLECTIONALPHA = false;
  41289. defines.GAMMAREFLECTION = false;
  41290. }
  41291. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41292. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41293. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41294. }
  41295. else {
  41296. defines.LIGHTMAP = false;
  41297. }
  41298. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41299. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41300. }
  41301. else {
  41302. defines.EMISSIVE = false;
  41303. }
  41304. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41305. if (this._metallicTexture) {
  41306. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41307. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41308. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41309. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41310. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41311. }
  41312. else if (this._reflectivityTexture) {
  41313. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41314. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41315. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41316. }
  41317. else {
  41318. defines.REFLECTIVITY = false;
  41319. }
  41320. if (this._microSurfaceTexture) {
  41321. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41322. }
  41323. else {
  41324. defines.MICROSURFACEMAP = false;
  41325. }
  41326. }
  41327. else {
  41328. defines.REFLECTIVITY = false;
  41329. defines.MICROSURFACEMAP = false;
  41330. }
  41331. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41332. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41333. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41334. defines.PARALLAX = true;
  41335. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41336. }
  41337. else {
  41338. defines.PARALLAX = false;
  41339. }
  41340. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41341. }
  41342. else {
  41343. defines.BUMP = false;
  41344. }
  41345. var refractionTexture = this._getRefractionTexture();
  41346. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41347. defines.REFRACTION = true;
  41348. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41349. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41350. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41351. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41352. if (this._linkRefractionWithTransparency) {
  41353. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41354. }
  41355. }
  41356. else {
  41357. defines.REFRACTION = false;
  41358. }
  41359. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41360. defines.ENVIRONMENTBRDF = true;
  41361. }
  41362. else {
  41363. defines.ENVIRONMENTBRDF = false;
  41364. }
  41365. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41366. defines.ALPHAFROMALBEDO = true;
  41367. }
  41368. else {
  41369. defines.ALPHAFROMALBEDO = false;
  41370. }
  41371. }
  41372. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41373. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41374. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41375. if (!this.backFaceCulling && this._twoSidedLighting) {
  41376. defines.TWOSIDEDLIGHTING = true;
  41377. }
  41378. else {
  41379. defines.TWOSIDEDLIGHTING = false;
  41380. }
  41381. defines.ALPHATESTVALUE = this._alphaCutOff;
  41382. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41383. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41384. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41385. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41386. }
  41387. if (defines._areImageProcessingDirty) {
  41388. this._imageProcessingConfiguration.prepareDefines(defines);
  41389. }
  41390. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41391. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41392. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41393. // Misc.
  41394. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41395. // Values that need to be evaluated on every frame
  41396. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41397. // Attribs
  41398. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41399. };
  41400. /**
  41401. * Force shader compilation
  41402. */
  41403. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41404. var _this = this;
  41405. var localOptions = __assign({ clipPlane: false }, options);
  41406. var defines = new PBRMaterialDefines();
  41407. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41408. if (effect.isReady()) {
  41409. if (onCompiled) {
  41410. onCompiled(this);
  41411. }
  41412. }
  41413. else {
  41414. effect.onCompileObservable.add(function () {
  41415. if (onCompiled) {
  41416. onCompiled(_this);
  41417. }
  41418. });
  41419. }
  41420. };
  41421. /**
  41422. * Initializes the uniform buffer layout for the shader.
  41423. */
  41424. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41425. // Order is important !
  41426. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41427. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41428. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41429. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41430. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41431. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41432. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41433. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41434. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41435. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41436. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41437. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41438. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41439. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41440. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41441. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41442. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41443. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41444. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41445. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41446. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41447. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41448. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41449. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41450. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41451. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41452. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41453. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41454. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41455. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41456. this._uniformBuffer.addUniform("pointSize", 1);
  41457. this._uniformBuffer.create();
  41458. };
  41459. /**
  41460. * Unbinds the textures.
  41461. */
  41462. PBRBaseMaterial.prototype.unbind = function () {
  41463. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41464. this._uniformBuffer.setTexture("reflectionSampler", null);
  41465. }
  41466. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41467. this._uniformBuffer.setTexture("refractionSampler", null);
  41468. }
  41469. _super.prototype.unbind.call(this);
  41470. };
  41471. /**
  41472. * Binds the submesh data.
  41473. * @param world - The world matrix.
  41474. * @param mesh - The BJS mesh.
  41475. * @param subMesh - A submesh of the BJS mesh.
  41476. */
  41477. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41478. var scene = this.getScene();
  41479. var defines = subMesh._materialDefines;
  41480. if (!defines) {
  41481. return;
  41482. }
  41483. var effect = subMesh.effect;
  41484. if (!effect) {
  41485. return;
  41486. }
  41487. this._activeEffect = effect;
  41488. // Matrices
  41489. this.bindOnlyWorldMatrix(world);
  41490. // Normal Matrix
  41491. if (defines.OBJECTSPACE_NORMALMAP) {
  41492. world.toNormalMatrix(this._normalMatrix);
  41493. this.bindOnlyNormalMatrix(this._normalMatrix);
  41494. }
  41495. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41496. // Bones
  41497. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41498. var reflectionTexture = null;
  41499. if (mustRebind) {
  41500. this._uniformBuffer.bindToEffect(effect, "Material");
  41501. this.bindViewProjection(effect);
  41502. reflectionTexture = this._getReflectionTexture();
  41503. var refractionTexture = this._getRefractionTexture();
  41504. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41505. // Texture uniforms
  41506. if (scene.texturesEnabled) {
  41507. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41508. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41509. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41510. }
  41511. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41512. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41513. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41514. }
  41515. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41516. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41517. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41518. }
  41519. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41520. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41521. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41522. if (reflectionTexture.boundingBoxSize) {
  41523. var cubeTexture = reflectionTexture;
  41524. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41525. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41526. }
  41527. var polynomials = reflectionTexture.sphericalPolynomial;
  41528. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41529. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41530. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41531. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41532. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41533. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41534. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41535. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41536. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41537. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41538. }
  41539. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41540. }
  41541. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41542. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41543. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41544. }
  41545. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41546. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41547. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41548. }
  41549. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41550. if (this._metallicTexture) {
  41551. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41552. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41553. }
  41554. else if (this._reflectivityTexture) {
  41555. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41556. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41557. }
  41558. if (this._microSurfaceTexture) {
  41559. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41560. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41561. }
  41562. }
  41563. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41564. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41565. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41566. if (scene._mirroredCameraPosition) {
  41567. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41568. }
  41569. else {
  41570. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41571. }
  41572. }
  41573. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41574. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41575. var depth = 1.0;
  41576. if (!refractionTexture.isCube) {
  41577. if (refractionTexture.depth) {
  41578. depth = refractionTexture.depth;
  41579. }
  41580. }
  41581. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41582. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41583. }
  41584. }
  41585. // Point size
  41586. if (this.pointsCloud) {
  41587. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41588. }
  41589. // Colors
  41590. if (defines.METALLICWORKFLOW) {
  41591. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41592. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41593. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41594. }
  41595. else {
  41596. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41597. }
  41598. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41599. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41600. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41601. // Misc
  41602. this._lightingInfos.x = this._directIntensity;
  41603. this._lightingInfos.y = this._emissiveIntensity;
  41604. this._lightingInfos.z = this._environmentIntensity;
  41605. this._lightingInfos.w = this._specularIntensity;
  41606. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41607. }
  41608. // Textures
  41609. if (scene.texturesEnabled) {
  41610. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41611. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41612. }
  41613. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41614. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41615. }
  41616. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41617. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41618. }
  41619. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41620. if (defines.LODBASEDMICROSFURACE) {
  41621. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41622. }
  41623. else {
  41624. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41625. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41626. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41627. }
  41628. }
  41629. if (defines.ENVIRONMENTBRDF) {
  41630. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41631. }
  41632. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41633. if (defines.LODBASEDMICROSFURACE) {
  41634. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41635. }
  41636. else {
  41637. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41638. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41639. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41640. }
  41641. }
  41642. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41643. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41644. }
  41645. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41646. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41647. }
  41648. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41649. if (this._metallicTexture) {
  41650. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41651. }
  41652. else if (this._reflectivityTexture) {
  41653. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41654. }
  41655. if (this._microSurfaceTexture) {
  41656. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41657. }
  41658. }
  41659. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41660. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41661. }
  41662. }
  41663. // Clip plane
  41664. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41665. // Colors
  41666. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41667. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41668. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41669. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41670. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41671. }
  41672. if (mustRebind || !this.isFrozen) {
  41673. // Lights
  41674. if (scene.lightsEnabled && !this._disableLighting) {
  41675. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41676. }
  41677. // View
  41678. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41679. this.bindView(effect);
  41680. }
  41681. // Fog
  41682. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41683. // Morph targets
  41684. if (defines.NUM_MORPH_INFLUENCERS) {
  41685. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41686. }
  41687. // image processing
  41688. this._imageProcessingConfiguration.bind(this._activeEffect);
  41689. // Log. depth
  41690. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41691. }
  41692. this._uniformBuffer.update();
  41693. this._afterBind(mesh);
  41694. };
  41695. /**
  41696. * Returns the animatable textures.
  41697. * @returns - Array of animatable textures.
  41698. */
  41699. PBRBaseMaterial.prototype.getAnimatables = function () {
  41700. var results = [];
  41701. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41702. results.push(this._albedoTexture);
  41703. }
  41704. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41705. results.push(this._ambientTexture);
  41706. }
  41707. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41708. results.push(this._opacityTexture);
  41709. }
  41710. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41711. results.push(this._reflectionTexture);
  41712. }
  41713. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41714. results.push(this._emissiveTexture);
  41715. }
  41716. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41717. results.push(this._metallicTexture);
  41718. }
  41719. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41720. results.push(this._reflectivityTexture);
  41721. }
  41722. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41723. results.push(this._bumpTexture);
  41724. }
  41725. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41726. results.push(this._lightmapTexture);
  41727. }
  41728. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41729. results.push(this._refractionTexture);
  41730. }
  41731. return results;
  41732. };
  41733. /**
  41734. * Returns the texture used for reflections.
  41735. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41736. */
  41737. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41738. if (this._reflectionTexture) {
  41739. return this._reflectionTexture;
  41740. }
  41741. return this.getScene().environmentTexture;
  41742. };
  41743. /**
  41744. * Returns the texture used for refraction or null if none is used.
  41745. * @returns - Refection texture if present. If no refraction texture and refraction
  41746. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41747. */
  41748. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41749. if (this._refractionTexture) {
  41750. return this._refractionTexture;
  41751. }
  41752. if (this._linkRefractionWithTransparency) {
  41753. return this.getScene().environmentTexture;
  41754. }
  41755. return null;
  41756. };
  41757. /**
  41758. * Disposes the resources of the material.
  41759. * @param forceDisposeEffect - Forces the disposal of effects.
  41760. * @param forceDisposeTextures - Forces the disposal of all textures.
  41761. */
  41762. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41763. if (forceDisposeTextures) {
  41764. if (this._albedoTexture) {
  41765. this._albedoTexture.dispose();
  41766. }
  41767. if (this._ambientTexture) {
  41768. this._ambientTexture.dispose();
  41769. }
  41770. if (this._opacityTexture) {
  41771. this._opacityTexture.dispose();
  41772. }
  41773. if (this._reflectionTexture) {
  41774. this._reflectionTexture.dispose();
  41775. }
  41776. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41777. this._environmentBRDFTexture.dispose();
  41778. }
  41779. if (this._emissiveTexture) {
  41780. this._emissiveTexture.dispose();
  41781. }
  41782. if (this._metallicTexture) {
  41783. this._metallicTexture.dispose();
  41784. }
  41785. if (this._reflectivityTexture) {
  41786. this._reflectivityTexture.dispose();
  41787. }
  41788. if (this._bumpTexture) {
  41789. this._bumpTexture.dispose();
  41790. }
  41791. if (this._lightmapTexture) {
  41792. this._lightmapTexture.dispose();
  41793. }
  41794. if (this._refractionTexture) {
  41795. this._refractionTexture.dispose();
  41796. }
  41797. }
  41798. this._renderTargets.dispose();
  41799. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41800. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41801. }
  41802. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41803. };
  41804. /**
  41805. * Stores the reflectivity values based on metallic roughness workflow.
  41806. */
  41807. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41808. __decorate([
  41809. BABYLON.serializeAsImageProcessingConfiguration()
  41810. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41811. __decorate([
  41812. BABYLON.serialize()
  41813. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41814. __decorate([
  41815. BABYLON.serialize()
  41816. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41817. return PBRBaseMaterial;
  41818. }(BABYLON.PushMaterial));
  41819. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41820. })(BABYLON || (BABYLON = {}));
  41821. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41822. var BABYLON;
  41823. (function (BABYLON) {
  41824. /**
  41825. * The Physically based simple base material of BJS.
  41826. *
  41827. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41828. * It is used as the base class for both the specGloss and metalRough conventions.
  41829. */
  41830. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41831. __extends(PBRBaseSimpleMaterial, _super);
  41832. /**
  41833. * Instantiates a new PBRMaterial instance.
  41834. *
  41835. * @param name The material name
  41836. * @param scene The scene the material will be use in.
  41837. */
  41838. function PBRBaseSimpleMaterial(name, scene) {
  41839. var _this = _super.call(this, name, scene) || this;
  41840. /**
  41841. * Number of Simultaneous lights allowed on the material.
  41842. */
  41843. _this.maxSimultaneousLights = 4;
  41844. /**
  41845. * If sets to true, disables all the lights affecting the material.
  41846. */
  41847. _this.disableLighting = false;
  41848. /**
  41849. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41850. */
  41851. _this.invertNormalMapX = false;
  41852. /**
  41853. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41854. */
  41855. _this.invertNormalMapY = false;
  41856. /**
  41857. * Emissivie color used to self-illuminate the model.
  41858. */
  41859. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41860. /**
  41861. * Occlusion Channel Strenght.
  41862. */
  41863. _this.occlusionStrength = 1.0;
  41864. _this.useLightmapAsShadowmap = false;
  41865. _this._useAlphaFromAlbedoTexture = true;
  41866. _this._useAmbientInGrayScale = true;
  41867. return _this;
  41868. }
  41869. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41870. /**
  41871. * Gets the current double sided mode.
  41872. */
  41873. get: function () {
  41874. return this._twoSidedLighting;
  41875. },
  41876. /**
  41877. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41878. */
  41879. set: function (value) {
  41880. if (this._twoSidedLighting === value) {
  41881. return;
  41882. }
  41883. this._twoSidedLighting = value;
  41884. this.backFaceCulling = !value;
  41885. this._markAllSubMeshesAsTexturesDirty();
  41886. },
  41887. enumerable: true,
  41888. configurable: true
  41889. });
  41890. /**
  41891. * Return the active textures of the material.
  41892. */
  41893. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41894. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41895. if (this.environmentTexture) {
  41896. activeTextures.push(this.environmentTexture);
  41897. }
  41898. if (this.normalTexture) {
  41899. activeTextures.push(this.normalTexture);
  41900. }
  41901. if (this.emissiveTexture) {
  41902. activeTextures.push(this.emissiveTexture);
  41903. }
  41904. if (this.occlusionTexture) {
  41905. activeTextures.push(this.occlusionTexture);
  41906. }
  41907. if (this.lightmapTexture) {
  41908. activeTextures.push(this.lightmapTexture);
  41909. }
  41910. return activeTextures;
  41911. };
  41912. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41913. if (_super.prototype.hasTexture.call(this, texture)) {
  41914. return true;
  41915. }
  41916. if (this.lightmapTexture === texture) {
  41917. return true;
  41918. }
  41919. return false;
  41920. };
  41921. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41922. return "PBRBaseSimpleMaterial";
  41923. };
  41924. __decorate([
  41925. BABYLON.serialize(),
  41926. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41927. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41928. __decorate([
  41929. BABYLON.serialize(),
  41930. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41931. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41932. __decorate([
  41933. BABYLON.serializeAsTexture(),
  41934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41935. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41936. __decorate([
  41937. BABYLON.serialize(),
  41938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41939. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41940. __decorate([
  41941. BABYLON.serialize(),
  41942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41943. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41944. __decorate([
  41945. BABYLON.serializeAsTexture(),
  41946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41947. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41948. __decorate([
  41949. BABYLON.serializeAsColor3("emissive"),
  41950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41951. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41952. __decorate([
  41953. BABYLON.serializeAsTexture(),
  41954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41955. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41956. __decorate([
  41957. BABYLON.serialize(),
  41958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41959. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41960. __decorate([
  41961. BABYLON.serializeAsTexture(),
  41962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41963. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41964. __decorate([
  41965. BABYLON.serialize(),
  41966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41967. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41968. __decorate([
  41969. BABYLON.serialize()
  41970. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41971. __decorate([
  41972. BABYLON.serializeAsTexture(),
  41973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41974. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41975. __decorate([
  41976. BABYLON.serialize(),
  41977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41978. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41979. return PBRBaseSimpleMaterial;
  41980. }(BABYLON.PBRBaseMaterial));
  41981. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41982. })(BABYLON || (BABYLON = {}));
  41983. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41984. var BABYLON;
  41985. (function (BABYLON) {
  41986. /**
  41987. * The Physically based material of BJS.
  41988. *
  41989. * This offers the main features of a standard PBR material.
  41990. * For more information, please refer to the documentation :
  41991. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41992. */
  41993. var PBRMaterial = /** @class */ (function (_super) {
  41994. __extends(PBRMaterial, _super);
  41995. /**
  41996. * Instantiates a new PBRMaterial instance.
  41997. *
  41998. * @param name The material name
  41999. * @param scene The scene the material will be use in.
  42000. */
  42001. function PBRMaterial(name, scene) {
  42002. var _this = _super.call(this, name, scene) || this;
  42003. /**
  42004. * Intensity of the direct lights e.g. the four lights available in your scene.
  42005. * This impacts both the direct diffuse and specular highlights.
  42006. */
  42007. _this.directIntensity = 1.0;
  42008. /**
  42009. * Intensity of the emissive part of the material.
  42010. * This helps controlling the emissive effect without modifying the emissive color.
  42011. */
  42012. _this.emissiveIntensity = 1.0;
  42013. /**
  42014. * Intensity of the environment e.g. how much the environment will light the object
  42015. * either through harmonics for rough material or through the refelction for shiny ones.
  42016. */
  42017. _this.environmentIntensity = 1.0;
  42018. /**
  42019. * This is a special control allowing the reduction of the specular highlights coming from the
  42020. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42021. */
  42022. _this.specularIntensity = 1.0;
  42023. /**
  42024. * Debug Control allowing disabling the bump map on this material.
  42025. */
  42026. _this.disableBumpMap = false;
  42027. /**
  42028. * AKA Occlusion Texture Intensity in other nomenclature.
  42029. */
  42030. _this.ambientTextureStrength = 1.0;
  42031. /**
  42032. * The color of a material in ambient lighting.
  42033. */
  42034. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42035. /**
  42036. * AKA Diffuse Color in other nomenclature.
  42037. */
  42038. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42039. /**
  42040. * AKA Specular Color in other nomenclature.
  42041. */
  42042. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42043. /**
  42044. * The color reflected from the material.
  42045. */
  42046. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42047. /**
  42048. * The color emitted from the material.
  42049. */
  42050. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42051. /**
  42052. * AKA Glossiness in other nomenclature.
  42053. */
  42054. _this.microSurface = 1.0;
  42055. /**
  42056. * source material index of refraction (IOR)' / 'destination material IOR.
  42057. */
  42058. _this.indexOfRefraction = 0.66;
  42059. /**
  42060. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42061. */
  42062. _this.invertRefractionY = false;
  42063. /**
  42064. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42065. * Materials half opaque for instance using refraction could benefit from this control.
  42066. */
  42067. _this.linkRefractionWithTransparency = false;
  42068. _this.useLightmapAsShadowmap = false;
  42069. /**
  42070. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42071. */
  42072. _this.useAlphaFromAlbedoTexture = false;
  42073. /**
  42074. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42075. */
  42076. _this.forceAlphaTest = false;
  42077. /**
  42078. * Defines the alpha limits in alpha test mode.
  42079. */
  42080. _this.alphaCutOff = 0.4;
  42081. /**
  42082. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42083. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42084. */
  42085. _this.useSpecularOverAlpha = true;
  42086. /**
  42087. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42088. */
  42089. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42090. /**
  42091. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42092. */
  42093. _this.useRoughnessFromMetallicTextureAlpha = true;
  42094. /**
  42095. * Specifies if the metallic texture contains the roughness information in its green channel.
  42096. */
  42097. _this.useRoughnessFromMetallicTextureGreen = false;
  42098. /**
  42099. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42100. */
  42101. _this.useMetallnessFromMetallicTextureBlue = false;
  42102. /**
  42103. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42104. */
  42105. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42106. /**
  42107. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42108. */
  42109. _this.useAmbientInGrayScale = false;
  42110. /**
  42111. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42112. * The material will try to infer what glossiness each pixel should be.
  42113. */
  42114. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42115. /**
  42116. * BJS is using an harcoded light falloff based on a manually sets up range.
  42117. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42118. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42119. */
  42120. _this.usePhysicalLightFalloff = true;
  42121. /**
  42122. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42123. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42124. */
  42125. _this.useRadianceOverAlpha = true;
  42126. /**
  42127. * Allows using an object space normal map (instead of tangent space).
  42128. */
  42129. _this.useObjectSpaceNormalMap = false;
  42130. /**
  42131. * Allows using the bump map in parallax mode.
  42132. */
  42133. _this.useParallax = false;
  42134. /**
  42135. * Allows using the bump map in parallax occlusion mode.
  42136. */
  42137. _this.useParallaxOcclusion = false;
  42138. /**
  42139. * Controls the scale bias of the parallax mode.
  42140. */
  42141. _this.parallaxScaleBias = 0.05;
  42142. /**
  42143. * If sets to true, disables all the lights affecting the material.
  42144. */
  42145. _this.disableLighting = false;
  42146. /**
  42147. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42148. */
  42149. _this.forceIrradianceInFragment = false;
  42150. /**
  42151. * Number of Simultaneous lights allowed on the material.
  42152. */
  42153. _this.maxSimultaneousLights = 4;
  42154. /**
  42155. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42156. */
  42157. _this.invertNormalMapX = false;
  42158. /**
  42159. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42160. */
  42161. _this.invertNormalMapY = false;
  42162. /**
  42163. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42164. */
  42165. _this.twoSidedLighting = false;
  42166. /**
  42167. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42168. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42169. */
  42170. _this.useAlphaFresnel = false;
  42171. /**
  42172. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42173. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42174. */
  42175. _this.useLinearAlphaFresnel = false;
  42176. /**
  42177. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42178. * And/Or occlude the blended part.
  42179. */
  42180. _this.environmentBRDFTexture = null;
  42181. /**
  42182. * Force normal to face away from face.
  42183. */
  42184. _this.forceNormalForward = false;
  42185. /**
  42186. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42187. * makes the reflect vector face the model (under horizon).
  42188. */
  42189. _this.useHorizonOcclusion = true;
  42190. /**
  42191. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42192. * too much the area relying on ambient texture to define their ambient occlusion.
  42193. */
  42194. _this.useRadianceOcclusion = true;
  42195. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42196. return _this;
  42197. }
  42198. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42199. /**
  42200. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42201. */
  42202. get: function () {
  42203. return this._PBRMATERIAL_OPAQUE;
  42204. },
  42205. enumerable: true,
  42206. configurable: true
  42207. });
  42208. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42209. /**
  42210. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42211. */
  42212. get: function () {
  42213. return this._PBRMATERIAL_ALPHATEST;
  42214. },
  42215. enumerable: true,
  42216. configurable: true
  42217. });
  42218. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42219. /**
  42220. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42221. */
  42222. get: function () {
  42223. return this._PBRMATERIAL_ALPHABLEND;
  42224. },
  42225. enumerable: true,
  42226. configurable: true
  42227. });
  42228. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42229. /**
  42230. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42231. * They are also discarded below the alpha cutoff threshold to improve performances.
  42232. */
  42233. get: function () {
  42234. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42235. },
  42236. enumerable: true,
  42237. configurable: true
  42238. });
  42239. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42240. /**
  42241. * Gets the image processing configuration used either in this material.
  42242. */
  42243. get: function () {
  42244. return this._imageProcessingConfiguration;
  42245. },
  42246. /**
  42247. * Sets the Default image processing configuration used either in the this material.
  42248. *
  42249. * If sets to null, the scene one is in use.
  42250. */
  42251. set: function (value) {
  42252. this._attachImageProcessingConfiguration(value);
  42253. // Ensure the effect will be rebuilt.
  42254. this._markAllSubMeshesAsTexturesDirty();
  42255. },
  42256. enumerable: true,
  42257. configurable: true
  42258. });
  42259. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42260. /**
  42261. * Gets wether the color curves effect is enabled.
  42262. */
  42263. get: function () {
  42264. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42265. },
  42266. /**
  42267. * Sets wether the color curves effect is enabled.
  42268. */
  42269. set: function (value) {
  42270. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42271. },
  42272. enumerable: true,
  42273. configurable: true
  42274. });
  42275. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42276. /**
  42277. * Gets wether the color grading effect is enabled.
  42278. */
  42279. get: function () {
  42280. return this.imageProcessingConfiguration.colorGradingEnabled;
  42281. },
  42282. /**
  42283. * Gets wether the color grading effect is enabled.
  42284. */
  42285. set: function (value) {
  42286. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42287. },
  42288. enumerable: true,
  42289. configurable: true
  42290. });
  42291. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42292. /**
  42293. * Gets wether tonemapping is enabled or not.
  42294. */
  42295. get: function () {
  42296. return this._imageProcessingConfiguration.toneMappingEnabled;
  42297. },
  42298. /**
  42299. * Sets wether tonemapping is enabled or not
  42300. */
  42301. set: function (value) {
  42302. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42303. },
  42304. enumerable: true,
  42305. configurable: true
  42306. });
  42307. ;
  42308. ;
  42309. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42310. /**
  42311. * The camera exposure used on this material.
  42312. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42313. * This corresponds to a photographic exposure.
  42314. */
  42315. get: function () {
  42316. return this._imageProcessingConfiguration.exposure;
  42317. },
  42318. /**
  42319. * The camera exposure used on this material.
  42320. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42321. * This corresponds to a photographic exposure.
  42322. */
  42323. set: function (value) {
  42324. this._imageProcessingConfiguration.exposure = value;
  42325. },
  42326. enumerable: true,
  42327. configurable: true
  42328. });
  42329. ;
  42330. ;
  42331. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42332. /**
  42333. * Gets The camera contrast used on this material.
  42334. */
  42335. get: function () {
  42336. return this._imageProcessingConfiguration.contrast;
  42337. },
  42338. /**
  42339. * Sets The camera contrast used on this material.
  42340. */
  42341. set: function (value) {
  42342. this._imageProcessingConfiguration.contrast = value;
  42343. },
  42344. enumerable: true,
  42345. configurable: true
  42346. });
  42347. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42348. /**
  42349. * Gets the Color Grading 2D Lookup Texture.
  42350. */
  42351. get: function () {
  42352. return this._imageProcessingConfiguration.colorGradingTexture;
  42353. },
  42354. /**
  42355. * Sets the Color Grading 2D Lookup Texture.
  42356. */
  42357. set: function (value) {
  42358. this._imageProcessingConfiguration.colorGradingTexture = value;
  42359. },
  42360. enumerable: true,
  42361. configurable: true
  42362. });
  42363. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42364. /**
  42365. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42366. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42367. * 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;
  42368. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42369. */
  42370. get: function () {
  42371. return this._imageProcessingConfiguration.colorCurves;
  42372. },
  42373. /**
  42374. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42375. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42376. * 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;
  42377. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42378. */
  42379. set: function (value) {
  42380. this._imageProcessingConfiguration.colorCurves = value;
  42381. },
  42382. enumerable: true,
  42383. configurable: true
  42384. });
  42385. /**
  42386. * Returns the name of this material class.
  42387. */
  42388. PBRMaterial.prototype.getClassName = function () {
  42389. return "PBRMaterial";
  42390. };
  42391. /**
  42392. * Returns an array of the actively used textures.
  42393. * @returns - Array of BaseTextures
  42394. */
  42395. PBRMaterial.prototype.getActiveTextures = function () {
  42396. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42397. if (this._albedoTexture) {
  42398. activeTextures.push(this._albedoTexture);
  42399. }
  42400. if (this._ambientTexture) {
  42401. activeTextures.push(this._ambientTexture);
  42402. }
  42403. if (this._opacityTexture) {
  42404. activeTextures.push(this._opacityTexture);
  42405. }
  42406. if (this._reflectionTexture) {
  42407. activeTextures.push(this._reflectionTexture);
  42408. }
  42409. if (this._emissiveTexture) {
  42410. activeTextures.push(this._emissiveTexture);
  42411. }
  42412. if (this._reflectivityTexture) {
  42413. activeTextures.push(this._reflectivityTexture);
  42414. }
  42415. if (this._metallicTexture) {
  42416. activeTextures.push(this._metallicTexture);
  42417. }
  42418. if (this._microSurfaceTexture) {
  42419. activeTextures.push(this._microSurfaceTexture);
  42420. }
  42421. if (this._bumpTexture) {
  42422. activeTextures.push(this._bumpTexture);
  42423. }
  42424. if (this._lightmapTexture) {
  42425. activeTextures.push(this._lightmapTexture);
  42426. }
  42427. if (this._refractionTexture) {
  42428. activeTextures.push(this._refractionTexture);
  42429. }
  42430. return activeTextures;
  42431. };
  42432. /**
  42433. * Checks to see if a texture is used in the material.
  42434. * @param texture - Base texture to use.
  42435. * @returns - Boolean specifying if a texture is used in the material.
  42436. */
  42437. PBRMaterial.prototype.hasTexture = function (texture) {
  42438. if (_super.prototype.hasTexture.call(this, texture)) {
  42439. return true;
  42440. }
  42441. if (this._albedoTexture === texture) {
  42442. return true;
  42443. }
  42444. if (this._ambientTexture === texture) {
  42445. return true;
  42446. }
  42447. if (this._opacityTexture === texture) {
  42448. return true;
  42449. }
  42450. if (this._reflectionTexture === texture) {
  42451. return true;
  42452. }
  42453. if (this._reflectivityTexture === texture) {
  42454. return true;
  42455. }
  42456. if (this._metallicTexture === texture) {
  42457. return true;
  42458. }
  42459. if (this._microSurfaceTexture === texture) {
  42460. return true;
  42461. }
  42462. if (this._bumpTexture === texture) {
  42463. return true;
  42464. }
  42465. if (this._lightmapTexture === texture) {
  42466. return true;
  42467. }
  42468. if (this._refractionTexture === texture) {
  42469. return true;
  42470. }
  42471. return false;
  42472. };
  42473. /**
  42474. * Makes a duplicate of the current material.
  42475. * @param name - name to use for the new material.
  42476. */
  42477. PBRMaterial.prototype.clone = function (name) {
  42478. var _this = this;
  42479. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42480. clone.id = name;
  42481. clone.name = name;
  42482. return clone;
  42483. };
  42484. /**
  42485. * Serializes this PBR Material.
  42486. * @returns - An object with the serialized material.
  42487. */
  42488. PBRMaterial.prototype.serialize = function () {
  42489. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42490. serializationObject.customType = "BABYLON.PBRMaterial";
  42491. return serializationObject;
  42492. };
  42493. // Statics
  42494. /**
  42495. * Parses a PBR Material from a serialized object.
  42496. * @param source - Serialized object.
  42497. * @param scene - BJS scene instance.
  42498. * @param rootUrl - url for the scene object
  42499. * @returns - PBRMaterial
  42500. */
  42501. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42502. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42503. };
  42504. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42505. /**
  42506. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42507. */
  42508. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42509. /**
  42510. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42511. */
  42512. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42513. /**
  42514. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42515. * They are also discarded below the alpha cutoff threshold to improve performances.
  42516. */
  42517. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42518. __decorate([
  42519. BABYLON.serialize(),
  42520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42521. ], PBRMaterial.prototype, "directIntensity", void 0);
  42522. __decorate([
  42523. BABYLON.serialize(),
  42524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42525. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42526. __decorate([
  42527. BABYLON.serialize(),
  42528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42529. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42530. __decorate([
  42531. BABYLON.serialize(),
  42532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42533. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42534. __decorate([
  42535. BABYLON.serialize(),
  42536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42537. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42538. __decorate([
  42539. BABYLON.serializeAsTexture(),
  42540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42541. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42542. __decorate([
  42543. BABYLON.serializeAsTexture(),
  42544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42545. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42546. __decorate([
  42547. BABYLON.serialize(),
  42548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42549. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42550. __decorate([
  42551. BABYLON.serializeAsTexture(),
  42552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42553. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42554. __decorate([
  42555. BABYLON.serializeAsTexture(),
  42556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42557. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42558. __decorate([
  42559. BABYLON.serializeAsTexture(),
  42560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42561. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42562. __decorate([
  42563. BABYLON.serializeAsTexture(),
  42564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42565. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42566. __decorate([
  42567. BABYLON.serializeAsTexture(),
  42568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42569. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42570. __decorate([
  42571. BABYLON.serialize(),
  42572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42573. ], PBRMaterial.prototype, "metallic", void 0);
  42574. __decorate([
  42575. BABYLON.serialize(),
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42577. ], PBRMaterial.prototype, "roughness", void 0);
  42578. __decorate([
  42579. BABYLON.serializeAsTexture(),
  42580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42581. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42582. __decorate([
  42583. BABYLON.serializeAsTexture(),
  42584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42585. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42586. __decorate([
  42587. BABYLON.serializeAsTexture(),
  42588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42589. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42590. __decorate([
  42591. BABYLON.serializeAsTexture(),
  42592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42593. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42594. __decorate([
  42595. BABYLON.serializeAsColor3("ambient"),
  42596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42597. ], PBRMaterial.prototype, "ambientColor", void 0);
  42598. __decorate([
  42599. BABYLON.serializeAsColor3("albedo"),
  42600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42601. ], PBRMaterial.prototype, "albedoColor", void 0);
  42602. __decorate([
  42603. BABYLON.serializeAsColor3("reflectivity"),
  42604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42605. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42606. __decorate([
  42607. BABYLON.serializeAsColor3("reflection"),
  42608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42609. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42610. __decorate([
  42611. BABYLON.serializeAsColor3("emissive"),
  42612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42613. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42614. __decorate([
  42615. BABYLON.serialize(),
  42616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42617. ], PBRMaterial.prototype, "microSurface", void 0);
  42618. __decorate([
  42619. BABYLON.serialize(),
  42620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42621. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42622. __decorate([
  42623. BABYLON.serialize(),
  42624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42625. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42626. __decorate([
  42627. BABYLON.serialize(),
  42628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42629. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42630. __decorate([
  42631. BABYLON.serialize(),
  42632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42633. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42634. __decorate([
  42635. BABYLON.serialize(),
  42636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42637. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42638. __decorate([
  42639. BABYLON.serialize(),
  42640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42641. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42642. __decorate([
  42643. BABYLON.serialize(),
  42644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42645. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42646. __decorate([
  42647. BABYLON.serialize(),
  42648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42649. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42650. __decorate([
  42651. BABYLON.serialize(),
  42652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42653. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42654. __decorate([
  42655. BABYLON.serialize(),
  42656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42657. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42658. __decorate([
  42659. BABYLON.serialize(),
  42660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42661. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42662. __decorate([
  42663. BABYLON.serialize(),
  42664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42665. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42666. __decorate([
  42667. BABYLON.serialize(),
  42668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42669. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42670. __decorate([
  42671. BABYLON.serialize(),
  42672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42673. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42674. __decorate([
  42675. BABYLON.serialize(),
  42676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42677. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42678. __decorate([
  42679. BABYLON.serialize(),
  42680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42681. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42682. __decorate([
  42683. BABYLON.serialize(),
  42684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42685. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42686. __decorate([
  42687. BABYLON.serialize(),
  42688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42689. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42690. __decorate([
  42691. BABYLON.serialize(),
  42692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42693. ], PBRMaterial.prototype, "useParallax", void 0);
  42694. __decorate([
  42695. BABYLON.serialize(),
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42697. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42698. __decorate([
  42699. BABYLON.serialize(),
  42700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42701. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42702. __decorate([
  42703. BABYLON.serialize(),
  42704. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42705. ], PBRMaterial.prototype, "disableLighting", void 0);
  42706. __decorate([
  42707. BABYLON.serialize(),
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42709. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42710. __decorate([
  42711. BABYLON.serialize(),
  42712. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42713. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42714. __decorate([
  42715. BABYLON.serialize(),
  42716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42717. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42718. __decorate([
  42719. BABYLON.serialize(),
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42721. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42722. __decorate([
  42723. BABYLON.serialize(),
  42724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42725. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42726. __decorate([
  42727. BABYLON.serialize(),
  42728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42729. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42730. __decorate([
  42731. BABYLON.serialize(),
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42734. __decorate([
  42735. BABYLON.serializeAsTexture(),
  42736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42737. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42738. __decorate([
  42739. BABYLON.serialize(),
  42740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42741. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42742. __decorate([
  42743. BABYLON.serialize(),
  42744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42745. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42746. __decorate([
  42747. BABYLON.serialize(),
  42748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42749. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42750. return PBRMaterial;
  42751. }(BABYLON.PBRBaseMaterial));
  42752. BABYLON.PBRMaterial = PBRMaterial;
  42753. })(BABYLON || (BABYLON = {}));
  42754. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42755. var BABYLON;
  42756. (function (BABYLON) {
  42757. /**
  42758. * The PBR material of BJS following the metal roughness convention.
  42759. *
  42760. * This fits to the PBR convention in the GLTF definition:
  42761. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42762. */
  42763. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42764. __extends(PBRMetallicRoughnessMaterial, _super);
  42765. /**
  42766. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42767. *
  42768. * @param name The material name
  42769. * @param scene The scene the material will be use in.
  42770. */
  42771. function PBRMetallicRoughnessMaterial(name, scene) {
  42772. var _this = _super.call(this, name, scene) || this;
  42773. _this._useRoughnessFromMetallicTextureAlpha = false;
  42774. _this._useRoughnessFromMetallicTextureGreen = true;
  42775. _this._useMetallnessFromMetallicTextureBlue = true;
  42776. _this.metallic = 1.0;
  42777. _this.roughness = 1.0;
  42778. return _this;
  42779. }
  42780. /**
  42781. * Return the currrent class name of the material.
  42782. */
  42783. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42784. return "PBRMetallicRoughnessMaterial";
  42785. };
  42786. /**
  42787. * Return the active textures of the material.
  42788. */
  42789. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42790. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42791. if (this.baseTexture) {
  42792. activeTextures.push(this.baseTexture);
  42793. }
  42794. if (this.metallicRoughnessTexture) {
  42795. activeTextures.push(this.metallicRoughnessTexture);
  42796. }
  42797. return activeTextures;
  42798. };
  42799. /**
  42800. * Checks to see if a texture is used in the material.
  42801. * @param texture - Base texture to use.
  42802. * @returns - Boolean specifying if a texture is used in the material.
  42803. */
  42804. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42805. if (_super.prototype.hasTexture.call(this, texture)) {
  42806. return true;
  42807. }
  42808. if (this.baseTexture === texture) {
  42809. return true;
  42810. }
  42811. if (this.metallicRoughnessTexture === texture) {
  42812. return true;
  42813. }
  42814. return false;
  42815. };
  42816. /**
  42817. * Makes a duplicate of the current material.
  42818. * @param name - name to use for the new material.
  42819. */
  42820. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42821. var _this = this;
  42822. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42823. clone.id = name;
  42824. clone.name = name;
  42825. return clone;
  42826. };
  42827. /**
  42828. * Serialize the material to a parsable JSON object.
  42829. */
  42830. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42831. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42832. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42833. return serializationObject;
  42834. };
  42835. /**
  42836. * Parses a JSON object correponding to the serialize function.
  42837. */
  42838. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42839. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42840. };
  42841. __decorate([
  42842. BABYLON.serializeAsColor3(),
  42843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42844. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42845. __decorate([
  42846. BABYLON.serializeAsTexture(),
  42847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42848. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42849. __decorate([
  42850. BABYLON.serialize(),
  42851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42852. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42853. __decorate([
  42854. BABYLON.serialize(),
  42855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42856. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42857. __decorate([
  42858. BABYLON.serializeAsTexture(),
  42859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42860. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42861. return PBRMetallicRoughnessMaterial;
  42862. }(BABYLON.PBRBaseSimpleMaterial));
  42863. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42864. })(BABYLON || (BABYLON = {}));
  42865. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42866. var BABYLON;
  42867. (function (BABYLON) {
  42868. /**
  42869. * The PBR material of BJS following the specular glossiness convention.
  42870. *
  42871. * This fits to the PBR convention in the GLTF definition:
  42872. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42873. */
  42874. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42875. __extends(PBRSpecularGlossinessMaterial, _super);
  42876. /**
  42877. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42878. *
  42879. * @param name The material name
  42880. * @param scene The scene the material will be use in.
  42881. */
  42882. function PBRSpecularGlossinessMaterial(name, scene) {
  42883. var _this = _super.call(this, name, scene) || this;
  42884. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42885. return _this;
  42886. }
  42887. /**
  42888. * Return the currrent class name of the material.
  42889. */
  42890. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42891. return "PBRSpecularGlossinessMaterial";
  42892. };
  42893. /**
  42894. * Return the active textures of the material.
  42895. */
  42896. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42897. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42898. if (this.diffuseTexture) {
  42899. activeTextures.push(this.diffuseTexture);
  42900. }
  42901. if (this.specularGlossinessTexture) {
  42902. activeTextures.push(this.specularGlossinessTexture);
  42903. }
  42904. return activeTextures;
  42905. };
  42906. /**
  42907. * Checks to see if a texture is used in the material.
  42908. * @param texture - Base texture to use.
  42909. * @returns - Boolean specifying if a texture is used in the material.
  42910. */
  42911. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42912. if (_super.prototype.hasTexture.call(this, texture)) {
  42913. return true;
  42914. }
  42915. if (this.diffuseTexture === texture) {
  42916. return true;
  42917. }
  42918. if (this.specularGlossinessTexture === texture) {
  42919. return true;
  42920. }
  42921. return false;
  42922. };
  42923. /**
  42924. * Makes a duplicate of the current material.
  42925. * @param name - name to use for the new material.
  42926. */
  42927. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42928. var _this = this;
  42929. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42930. clone.id = name;
  42931. clone.name = name;
  42932. return clone;
  42933. };
  42934. /**
  42935. * Serialize the material to a parsable JSON object.
  42936. */
  42937. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42938. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42939. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42940. return serializationObject;
  42941. };
  42942. /**
  42943. * Parses a JSON object correponding to the serialize function.
  42944. */
  42945. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42946. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42947. };
  42948. __decorate([
  42949. BABYLON.serializeAsColor3("diffuse"),
  42950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42951. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42952. __decorate([
  42953. BABYLON.serializeAsTexture(),
  42954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42955. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42956. __decorate([
  42957. BABYLON.serializeAsColor3("specular"),
  42958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42959. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42960. __decorate([
  42961. BABYLON.serialize(),
  42962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42963. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42964. __decorate([
  42965. BABYLON.serializeAsTexture(),
  42966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42967. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42968. return PBRSpecularGlossinessMaterial;
  42969. }(BABYLON.PBRBaseSimpleMaterial));
  42970. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42971. })(BABYLON || (BABYLON = {}));
  42972. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42973. var BABYLON;
  42974. (function (BABYLON) {
  42975. BABYLON.CameraInputTypes = {};
  42976. var CameraInputsManager = /** @class */ (function () {
  42977. function CameraInputsManager(camera) {
  42978. this.attached = {};
  42979. this.camera = camera;
  42980. this.checkInputs = function () { };
  42981. }
  42982. /**
  42983. * Add an input method to a camera.
  42984. * builtin inputs example: camera.inputs.addGamepad();
  42985. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42986. * @param input camera input method
  42987. */
  42988. CameraInputsManager.prototype.add = function (input) {
  42989. var type = input.getSimpleName();
  42990. if (this.attached[type]) {
  42991. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42992. return;
  42993. }
  42994. this.attached[type] = input;
  42995. input.camera = this.camera;
  42996. //for checkInputs, we are dynamically creating a function
  42997. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42998. if (input.checkInputs) {
  42999. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43000. }
  43001. if (this.attachedElement) {
  43002. input.attachControl(this.attachedElement);
  43003. }
  43004. };
  43005. /**
  43006. * Remove a specific input method from a camera
  43007. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43008. * @param inputToRemove camera input method
  43009. */
  43010. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43011. for (var cam in this.attached) {
  43012. var input = this.attached[cam];
  43013. if (input === inputToRemove) {
  43014. input.detachControl(this.attachedElement);
  43015. input.camera = null;
  43016. delete this.attached[cam];
  43017. this.rebuildInputCheck();
  43018. }
  43019. }
  43020. };
  43021. CameraInputsManager.prototype.removeByType = function (inputType) {
  43022. for (var cam in this.attached) {
  43023. var input = this.attached[cam];
  43024. if (input.getClassName() === inputType) {
  43025. input.detachControl(this.attachedElement);
  43026. input.camera = null;
  43027. delete this.attached[cam];
  43028. this.rebuildInputCheck();
  43029. }
  43030. }
  43031. };
  43032. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43033. var current = this.checkInputs;
  43034. return function () {
  43035. current();
  43036. fn();
  43037. };
  43038. };
  43039. CameraInputsManager.prototype.attachInput = function (input) {
  43040. if (this.attachedElement) {
  43041. input.attachControl(this.attachedElement, this.noPreventDefault);
  43042. }
  43043. };
  43044. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43045. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43046. if (this.attachedElement) {
  43047. return;
  43048. }
  43049. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43050. this.attachedElement = element;
  43051. this.noPreventDefault = noPreventDefault;
  43052. for (var cam in this.attached) {
  43053. this.attached[cam].attachControl(element, noPreventDefault);
  43054. }
  43055. };
  43056. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43057. if (disconnect === void 0) { disconnect = false; }
  43058. if (this.attachedElement !== element) {
  43059. return;
  43060. }
  43061. for (var cam in this.attached) {
  43062. this.attached[cam].detachControl(element);
  43063. if (disconnect) {
  43064. this.attached[cam].camera = null;
  43065. }
  43066. }
  43067. this.attachedElement = null;
  43068. };
  43069. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43070. this.checkInputs = function () { };
  43071. for (var cam in this.attached) {
  43072. var input = this.attached[cam];
  43073. if (input.checkInputs) {
  43074. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43075. }
  43076. }
  43077. };
  43078. /**
  43079. * Remove all attached input methods from a camera
  43080. */
  43081. CameraInputsManager.prototype.clear = function () {
  43082. if (this.attachedElement) {
  43083. this.detachElement(this.attachedElement, true);
  43084. }
  43085. this.attached = {};
  43086. this.attachedElement = null;
  43087. this.checkInputs = function () { };
  43088. };
  43089. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43090. var inputs = {};
  43091. for (var cam in this.attached) {
  43092. var input = this.attached[cam];
  43093. var res = BABYLON.SerializationHelper.Serialize(input);
  43094. inputs[input.getClassName()] = res;
  43095. }
  43096. serializedCamera.inputsmgr = inputs;
  43097. };
  43098. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43099. var parsedInputs = parsedCamera.inputsmgr;
  43100. if (parsedInputs) {
  43101. this.clear();
  43102. for (var n in parsedInputs) {
  43103. var construct = BABYLON.CameraInputTypes[n];
  43104. if (construct) {
  43105. var parsedinput = parsedInputs[n];
  43106. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43107. this.add(input);
  43108. }
  43109. }
  43110. }
  43111. else {
  43112. //2016-03-08 this part is for managing backward compatibility
  43113. for (var n in this.attached) {
  43114. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43115. if (construct) {
  43116. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43117. this.remove(this.attached[n]);
  43118. this.add(input);
  43119. }
  43120. }
  43121. }
  43122. };
  43123. return CameraInputsManager;
  43124. }());
  43125. BABYLON.CameraInputsManager = CameraInputsManager;
  43126. })(BABYLON || (BABYLON = {}));
  43127. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43128. var BABYLON;
  43129. (function (BABYLON) {
  43130. var TargetCamera = /** @class */ (function (_super) {
  43131. __extends(TargetCamera, _super);
  43132. function TargetCamera(name, position, scene) {
  43133. var _this = _super.call(this, name, position, scene) || this;
  43134. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43135. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43136. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43137. _this.speed = 2.0;
  43138. _this.noRotationConstraint = false;
  43139. _this.lockedTarget = null;
  43140. _this._currentTarget = BABYLON.Vector3.Zero();
  43141. _this._viewMatrix = BABYLON.Matrix.Zero();
  43142. _this._camMatrix = BABYLON.Matrix.Zero();
  43143. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43144. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43145. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43146. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43147. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43148. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43149. _this._tempMatrix = BABYLON.Matrix.Zero();
  43150. return _this;
  43151. }
  43152. TargetCamera.prototype.getFrontPosition = function (distance) {
  43153. this.getWorldMatrix();
  43154. var direction = this.getTarget().subtract(this.position);
  43155. direction.normalize();
  43156. direction.scaleInPlace(distance);
  43157. return this.globalPosition.add(direction);
  43158. };
  43159. TargetCamera.prototype._getLockedTargetPosition = function () {
  43160. if (!this.lockedTarget) {
  43161. return null;
  43162. }
  43163. if (this.lockedTarget.absolutePosition) {
  43164. this.lockedTarget.computeWorldMatrix();
  43165. }
  43166. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43167. };
  43168. TargetCamera.prototype.storeState = function () {
  43169. this._storedPosition = this.position.clone();
  43170. this._storedRotation = this.rotation.clone();
  43171. if (this.rotationQuaternion) {
  43172. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43173. }
  43174. return _super.prototype.storeState.call(this);
  43175. };
  43176. /**
  43177. * Restored camera state. You must call storeState() first
  43178. */
  43179. TargetCamera.prototype._restoreStateValues = function () {
  43180. if (!_super.prototype._restoreStateValues.call(this)) {
  43181. return false;
  43182. }
  43183. this.position = this._storedPosition.clone();
  43184. this.rotation = this._storedRotation.clone();
  43185. if (this.rotationQuaternion) {
  43186. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43187. }
  43188. this.cameraDirection.copyFromFloats(0, 0, 0);
  43189. this.cameraRotation.copyFromFloats(0, 0);
  43190. return true;
  43191. };
  43192. // Cache
  43193. TargetCamera.prototype._initCache = function () {
  43194. _super.prototype._initCache.call(this);
  43195. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43196. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43197. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43198. };
  43199. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43200. if (!ignoreParentClass) {
  43201. _super.prototype._updateCache.call(this);
  43202. }
  43203. var lockedTargetPosition = this._getLockedTargetPosition();
  43204. if (!lockedTargetPosition) {
  43205. this._cache.lockedTarget = null;
  43206. }
  43207. else {
  43208. if (!this._cache.lockedTarget) {
  43209. this._cache.lockedTarget = lockedTargetPosition.clone();
  43210. }
  43211. else {
  43212. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43213. }
  43214. }
  43215. this._cache.rotation.copyFrom(this.rotation);
  43216. if (this.rotationQuaternion)
  43217. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43218. };
  43219. // Synchronized
  43220. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43221. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43222. return false;
  43223. }
  43224. var lockedTargetPosition = this._getLockedTargetPosition();
  43225. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43226. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43227. };
  43228. // Methods
  43229. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43230. var engine = this.getEngine();
  43231. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43232. };
  43233. // Target
  43234. TargetCamera.prototype.setTarget = function (target) {
  43235. this.upVector.normalize();
  43236. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43237. this._camMatrix.invert();
  43238. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43239. var vDir = target.subtract(this.position);
  43240. if (vDir.x >= 0.0) {
  43241. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43242. }
  43243. else {
  43244. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43245. }
  43246. this.rotation.z = 0;
  43247. if (isNaN(this.rotation.x)) {
  43248. this.rotation.x = 0;
  43249. }
  43250. if (isNaN(this.rotation.y)) {
  43251. this.rotation.y = 0;
  43252. }
  43253. if (isNaN(this.rotation.z)) {
  43254. this.rotation.z = 0;
  43255. }
  43256. if (this.rotationQuaternion) {
  43257. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43258. }
  43259. };
  43260. /**
  43261. * Return the current target position of the camera. This value is expressed in local space.
  43262. */
  43263. TargetCamera.prototype.getTarget = function () {
  43264. return this._currentTarget;
  43265. };
  43266. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43267. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43268. };
  43269. TargetCamera.prototype._updatePosition = function () {
  43270. if (this.parent) {
  43271. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43272. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43273. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43274. return;
  43275. }
  43276. this.position.addInPlace(this.cameraDirection);
  43277. };
  43278. TargetCamera.prototype._checkInputs = function () {
  43279. var needToMove = this._decideIfNeedsToMove();
  43280. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43281. // Move
  43282. if (needToMove) {
  43283. this._updatePosition();
  43284. }
  43285. // Rotate
  43286. if (needToRotate) {
  43287. this.rotation.x += this.cameraRotation.x;
  43288. this.rotation.y += this.cameraRotation.y;
  43289. //rotate, if quaternion is set and rotation was used
  43290. if (this.rotationQuaternion) {
  43291. var len = this.rotation.lengthSquared();
  43292. if (len) {
  43293. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43294. }
  43295. }
  43296. if (!this.noRotationConstraint) {
  43297. var limit = (Math.PI / 2) * 0.95;
  43298. if (this.rotation.x > limit)
  43299. this.rotation.x = limit;
  43300. if (this.rotation.x < -limit)
  43301. this.rotation.x = -limit;
  43302. }
  43303. }
  43304. // Inertia
  43305. if (needToMove) {
  43306. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43307. this.cameraDirection.x = 0;
  43308. }
  43309. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43310. this.cameraDirection.y = 0;
  43311. }
  43312. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43313. this.cameraDirection.z = 0;
  43314. }
  43315. this.cameraDirection.scaleInPlace(this.inertia);
  43316. }
  43317. if (needToRotate) {
  43318. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43319. this.cameraRotation.x = 0;
  43320. }
  43321. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43322. this.cameraRotation.y = 0;
  43323. }
  43324. this.cameraRotation.scaleInPlace(this.inertia);
  43325. }
  43326. _super.prototype._checkInputs.call(this);
  43327. };
  43328. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43329. if (this.rotationQuaternion) {
  43330. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43331. }
  43332. else {
  43333. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43334. }
  43335. //update the up vector!
  43336. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43337. };
  43338. TargetCamera.prototype._getViewMatrix = function () {
  43339. if (this.lockedTarget) {
  43340. this.setTarget(this._getLockedTargetPosition());
  43341. }
  43342. // Compute
  43343. this._updateCameraRotationMatrix();
  43344. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43345. // Computing target and final matrix
  43346. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43347. if (this.getScene().useRightHandedSystem) {
  43348. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43349. }
  43350. else {
  43351. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43352. }
  43353. return this._viewMatrix;
  43354. };
  43355. /**
  43356. * @override
  43357. * Override Camera.createRigCamera
  43358. */
  43359. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43360. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43361. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43362. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43363. if (!this.rotationQuaternion) {
  43364. this.rotationQuaternion = new BABYLON.Quaternion();
  43365. }
  43366. rigCamera._cameraRigParams = {};
  43367. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43368. }
  43369. return rigCamera;
  43370. }
  43371. return null;
  43372. };
  43373. /**
  43374. * @override
  43375. * Override Camera._updateRigCameras
  43376. */
  43377. TargetCamera.prototype._updateRigCameras = function () {
  43378. var camLeft = this._rigCameras[0];
  43379. var camRight = this._rigCameras[1];
  43380. switch (this.cameraRigMode) {
  43381. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43382. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43383. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43384. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43385. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43386. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43387. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43388. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43389. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43390. camLeft.setTarget(this.getTarget());
  43391. camRight.setTarget(this.getTarget());
  43392. break;
  43393. case BABYLON.Camera.RIG_MODE_VR:
  43394. if (camLeft.rotationQuaternion) {
  43395. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43396. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43397. }
  43398. else {
  43399. camLeft.rotation.copyFrom(this.rotation);
  43400. camRight.rotation.copyFrom(this.rotation);
  43401. }
  43402. camLeft.position.copyFrom(this.position);
  43403. camRight.position.copyFrom(this.position);
  43404. break;
  43405. }
  43406. _super.prototype._updateRigCameras.call(this);
  43407. };
  43408. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43409. if (!this._rigCamTransformMatrix) {
  43410. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43411. }
  43412. var target = this.getTarget();
  43413. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43414. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43415. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43416. };
  43417. TargetCamera.prototype.getClassName = function () {
  43418. return "TargetCamera";
  43419. };
  43420. __decorate([
  43421. BABYLON.serializeAsVector3()
  43422. ], TargetCamera.prototype, "rotation", void 0);
  43423. __decorate([
  43424. BABYLON.serialize()
  43425. ], TargetCamera.prototype, "speed", void 0);
  43426. __decorate([
  43427. BABYLON.serializeAsMeshReference("lockedTargetId")
  43428. ], TargetCamera.prototype, "lockedTarget", void 0);
  43429. return TargetCamera;
  43430. }(BABYLON.Camera));
  43431. BABYLON.TargetCamera = TargetCamera;
  43432. })(BABYLON || (BABYLON = {}));
  43433. //# sourceMappingURL=babylon.targetCamera.js.map
  43434. var BABYLON;
  43435. (function (BABYLON) {
  43436. var FreeCameraMouseInput = /** @class */ (function () {
  43437. function FreeCameraMouseInput(touchEnabled) {
  43438. if (touchEnabled === void 0) { touchEnabled = true; }
  43439. this.touchEnabled = touchEnabled;
  43440. this.buttons = [0, 1, 2];
  43441. this.angularSensibility = 2000.0;
  43442. this.previousPosition = null;
  43443. }
  43444. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43445. var _this = this;
  43446. var engine = this.camera.getEngine();
  43447. if (!this._pointerInput) {
  43448. this._pointerInput = function (p, s) {
  43449. var evt = p.event;
  43450. if (engine.isInVRExclusivePointerMode) {
  43451. return;
  43452. }
  43453. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43454. return;
  43455. }
  43456. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43457. return;
  43458. }
  43459. var srcElement = (evt.srcElement || evt.target);
  43460. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43461. try {
  43462. srcElement.setPointerCapture(evt.pointerId);
  43463. }
  43464. catch (e) {
  43465. //Nothing to do with the error. Execution will continue.
  43466. }
  43467. _this.previousPosition = {
  43468. x: evt.clientX,
  43469. y: evt.clientY
  43470. };
  43471. if (!noPreventDefault) {
  43472. evt.preventDefault();
  43473. element.focus();
  43474. }
  43475. }
  43476. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43477. try {
  43478. srcElement.releasePointerCapture(evt.pointerId);
  43479. }
  43480. catch (e) {
  43481. //Nothing to do with the error.
  43482. }
  43483. _this.previousPosition = null;
  43484. if (!noPreventDefault) {
  43485. evt.preventDefault();
  43486. }
  43487. }
  43488. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43489. if (!_this.previousPosition || engine.isPointerLock) {
  43490. return;
  43491. }
  43492. var offsetX = evt.clientX - _this.previousPosition.x;
  43493. var offsetY = evt.clientY - _this.previousPosition.y;
  43494. if (_this.camera.getScene().useRightHandedSystem) {
  43495. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43496. }
  43497. else {
  43498. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43499. }
  43500. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43501. _this.previousPosition = {
  43502. x: evt.clientX,
  43503. y: evt.clientY
  43504. };
  43505. if (!noPreventDefault) {
  43506. evt.preventDefault();
  43507. }
  43508. }
  43509. };
  43510. }
  43511. this._onMouseMove = function (evt) {
  43512. if (!engine.isPointerLock) {
  43513. return;
  43514. }
  43515. if (engine.isInVRExclusivePointerMode) {
  43516. return;
  43517. }
  43518. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43519. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43520. if (_this.camera.getScene().useRightHandedSystem) {
  43521. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43522. }
  43523. else {
  43524. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43525. }
  43526. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43527. _this.previousPosition = null;
  43528. if (!noPreventDefault) {
  43529. evt.preventDefault();
  43530. }
  43531. };
  43532. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43533. element.addEventListener("mousemove", this._onMouseMove, false);
  43534. };
  43535. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43536. if (this._observer && element) {
  43537. this.camera.getScene().onPointerObservable.remove(this._observer);
  43538. if (this._onMouseMove) {
  43539. element.removeEventListener("mousemove", this._onMouseMove);
  43540. }
  43541. this._observer = null;
  43542. this._onMouseMove = null;
  43543. this.previousPosition = null;
  43544. }
  43545. };
  43546. FreeCameraMouseInput.prototype.getClassName = function () {
  43547. return "FreeCameraMouseInput";
  43548. };
  43549. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43550. return "mouse";
  43551. };
  43552. __decorate([
  43553. BABYLON.serialize()
  43554. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43555. __decorate([
  43556. BABYLON.serialize()
  43557. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43558. return FreeCameraMouseInput;
  43559. }());
  43560. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43561. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43562. })(BABYLON || (BABYLON = {}));
  43563. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43564. var BABYLON;
  43565. (function (BABYLON) {
  43566. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43567. function FreeCameraKeyboardMoveInput() {
  43568. this._keys = new Array();
  43569. this.keysUp = [38];
  43570. this.keysDown = [40];
  43571. this.keysLeft = [37];
  43572. this.keysRight = [39];
  43573. }
  43574. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43575. var _this = this;
  43576. if (this._onCanvasBlurObserver) {
  43577. return;
  43578. }
  43579. this._scene = this.camera.getScene();
  43580. this._engine = this._scene.getEngine();
  43581. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43582. _this._keys = [];
  43583. });
  43584. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43585. var evt = info.event;
  43586. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43587. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43588. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43589. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43590. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43591. var index = _this._keys.indexOf(evt.keyCode);
  43592. if (index === -1) {
  43593. _this._keys.push(evt.keyCode);
  43594. }
  43595. if (!noPreventDefault) {
  43596. evt.preventDefault();
  43597. }
  43598. }
  43599. }
  43600. else {
  43601. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43602. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43603. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43604. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43605. var index = _this._keys.indexOf(evt.keyCode);
  43606. if (index >= 0) {
  43607. _this._keys.splice(index, 1);
  43608. }
  43609. if (!noPreventDefault) {
  43610. evt.preventDefault();
  43611. }
  43612. }
  43613. }
  43614. });
  43615. };
  43616. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43617. if (this._scene) {
  43618. if (this._onKeyboardObserver) {
  43619. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43620. }
  43621. if (this._onCanvasBlurObserver) {
  43622. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43623. }
  43624. this._onKeyboardObserver = null;
  43625. this._onCanvasBlurObserver = null;
  43626. }
  43627. this._keys = [];
  43628. };
  43629. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43630. if (this._onKeyboardObserver) {
  43631. var camera = this.camera;
  43632. // Keyboard
  43633. for (var index = 0; index < this._keys.length; index++) {
  43634. var keyCode = this._keys[index];
  43635. var speed = camera._computeLocalCameraSpeed();
  43636. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43637. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43638. }
  43639. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43640. camera._localDirection.copyFromFloats(0, 0, speed);
  43641. }
  43642. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43643. camera._localDirection.copyFromFloats(speed, 0, 0);
  43644. }
  43645. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43646. camera._localDirection.copyFromFloats(0, 0, -speed);
  43647. }
  43648. if (camera.getScene().useRightHandedSystem) {
  43649. camera._localDirection.z *= -1;
  43650. }
  43651. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43652. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43653. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43654. }
  43655. }
  43656. };
  43657. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43658. return "FreeCameraKeyboardMoveInput";
  43659. };
  43660. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43661. this._keys = [];
  43662. };
  43663. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43664. return "keyboard";
  43665. };
  43666. __decorate([
  43667. BABYLON.serialize()
  43668. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43669. __decorate([
  43670. BABYLON.serialize()
  43671. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43672. __decorate([
  43673. BABYLON.serialize()
  43674. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43675. __decorate([
  43676. BABYLON.serialize()
  43677. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43678. return FreeCameraKeyboardMoveInput;
  43679. }());
  43680. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43681. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43682. })(BABYLON || (BABYLON = {}));
  43683. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43684. var BABYLON;
  43685. (function (BABYLON) {
  43686. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43687. __extends(FreeCameraInputsManager, _super);
  43688. function FreeCameraInputsManager(camera) {
  43689. return _super.call(this, camera) || this;
  43690. }
  43691. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43692. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43693. return this;
  43694. };
  43695. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43696. if (touchEnabled === void 0) { touchEnabled = true; }
  43697. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43698. return this;
  43699. };
  43700. FreeCameraInputsManager.prototype.addGamepad = function () {
  43701. this.add(new BABYLON.FreeCameraGamepadInput());
  43702. return this;
  43703. };
  43704. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43705. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43706. return this;
  43707. };
  43708. FreeCameraInputsManager.prototype.addTouch = function () {
  43709. this.add(new BABYLON.FreeCameraTouchInput());
  43710. return this;
  43711. };
  43712. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43713. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43714. return this;
  43715. };
  43716. return FreeCameraInputsManager;
  43717. }(BABYLON.CameraInputsManager));
  43718. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43719. })(BABYLON || (BABYLON = {}));
  43720. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43721. var BABYLON;
  43722. (function (BABYLON) {
  43723. var FreeCamera = /** @class */ (function (_super) {
  43724. __extends(FreeCamera, _super);
  43725. function FreeCamera(name, position, scene) {
  43726. var _this = _super.call(this, name, position, scene) || this;
  43727. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43728. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43729. _this.checkCollisions = false;
  43730. _this.applyGravity = false;
  43731. _this._needMoveForGravity = false;
  43732. _this._oldPosition = BABYLON.Vector3.Zero();
  43733. _this._diffPosition = BABYLON.Vector3.Zero();
  43734. _this._newPosition = BABYLON.Vector3.Zero();
  43735. // Collisions
  43736. _this._collisionMask = -1;
  43737. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43738. if (collidedMesh === void 0) { collidedMesh = null; }
  43739. //TODO move this to the collision coordinator!
  43740. if (_this.getScene().workerCollisions)
  43741. newPosition.multiplyInPlace(_this._collider._radius);
  43742. var updatePosition = function (newPos) {
  43743. _this._newPosition.copyFrom(newPos);
  43744. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43745. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43746. _this.position.addInPlace(_this._diffPosition);
  43747. if (_this.onCollide && collidedMesh) {
  43748. _this.onCollide(collidedMesh);
  43749. }
  43750. }
  43751. };
  43752. updatePosition(newPosition);
  43753. };
  43754. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43755. _this.inputs.addKeyboard().addMouse();
  43756. return _this;
  43757. }
  43758. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43759. //-- begin properties for backward compatibility for inputs
  43760. /**
  43761. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43762. * Higher values reduce sensitivity.
  43763. */
  43764. get: function () {
  43765. var mouse = this.inputs.attached["mouse"];
  43766. if (mouse)
  43767. return mouse.angularSensibility;
  43768. return 0;
  43769. },
  43770. /**
  43771. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43772. * Higher values reduce sensitivity.
  43773. */
  43774. set: function (value) {
  43775. var mouse = this.inputs.attached["mouse"];
  43776. if (mouse)
  43777. mouse.angularSensibility = value;
  43778. },
  43779. enumerable: true,
  43780. configurable: true
  43781. });
  43782. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43783. get: function () {
  43784. var keyboard = this.inputs.attached["keyboard"];
  43785. if (keyboard)
  43786. return keyboard.keysUp;
  43787. return [];
  43788. },
  43789. set: function (value) {
  43790. var keyboard = this.inputs.attached["keyboard"];
  43791. if (keyboard)
  43792. keyboard.keysUp = value;
  43793. },
  43794. enumerable: true,
  43795. configurable: true
  43796. });
  43797. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43798. get: function () {
  43799. var keyboard = this.inputs.attached["keyboard"];
  43800. if (keyboard)
  43801. return keyboard.keysDown;
  43802. return [];
  43803. },
  43804. set: function (value) {
  43805. var keyboard = this.inputs.attached["keyboard"];
  43806. if (keyboard)
  43807. keyboard.keysDown = value;
  43808. },
  43809. enumerable: true,
  43810. configurable: true
  43811. });
  43812. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43813. get: function () {
  43814. var keyboard = this.inputs.attached["keyboard"];
  43815. if (keyboard)
  43816. return keyboard.keysLeft;
  43817. return [];
  43818. },
  43819. set: function (value) {
  43820. var keyboard = this.inputs.attached["keyboard"];
  43821. if (keyboard)
  43822. keyboard.keysLeft = value;
  43823. },
  43824. enumerable: true,
  43825. configurable: true
  43826. });
  43827. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43828. get: function () {
  43829. var keyboard = this.inputs.attached["keyboard"];
  43830. if (keyboard)
  43831. return keyboard.keysRight;
  43832. return [];
  43833. },
  43834. set: function (value) {
  43835. var keyboard = this.inputs.attached["keyboard"];
  43836. if (keyboard)
  43837. keyboard.keysRight = value;
  43838. },
  43839. enumerable: true,
  43840. configurable: true
  43841. });
  43842. // Controls
  43843. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43844. this.inputs.attachElement(element, noPreventDefault);
  43845. };
  43846. FreeCamera.prototype.detachControl = function (element) {
  43847. this.inputs.detachElement(element);
  43848. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43849. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43850. };
  43851. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43852. get: function () {
  43853. return this._collisionMask;
  43854. },
  43855. set: function (mask) {
  43856. this._collisionMask = !isNaN(mask) ? mask : -1;
  43857. },
  43858. enumerable: true,
  43859. configurable: true
  43860. });
  43861. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43862. var globalPosition;
  43863. if (this.parent) {
  43864. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43865. }
  43866. else {
  43867. globalPosition = this.position;
  43868. }
  43869. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43870. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43871. if (!this._collider) {
  43872. this._collider = new BABYLON.Collider();
  43873. }
  43874. this._collider._radius = this.ellipsoid;
  43875. this._collider.collisionMask = this._collisionMask;
  43876. //no need for clone, as long as gravity is not on.
  43877. var actualDisplacement = displacement;
  43878. //add gravity to the direction to prevent the dual-collision checking
  43879. if (this.applyGravity) {
  43880. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43881. actualDisplacement = displacement.add(this.getScene().gravity);
  43882. }
  43883. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43884. };
  43885. FreeCamera.prototype._checkInputs = function () {
  43886. if (!this._localDirection) {
  43887. this._localDirection = BABYLON.Vector3.Zero();
  43888. this._transformedDirection = BABYLON.Vector3.Zero();
  43889. }
  43890. this.inputs.checkInputs();
  43891. _super.prototype._checkInputs.call(this);
  43892. };
  43893. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43894. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43895. };
  43896. FreeCamera.prototype._updatePosition = function () {
  43897. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43898. this._collideWithWorld(this.cameraDirection);
  43899. }
  43900. else {
  43901. _super.prototype._updatePosition.call(this);
  43902. }
  43903. };
  43904. FreeCamera.prototype.dispose = function () {
  43905. this.inputs.clear();
  43906. _super.prototype.dispose.call(this);
  43907. };
  43908. FreeCamera.prototype.getClassName = function () {
  43909. return "FreeCamera";
  43910. };
  43911. __decorate([
  43912. BABYLON.serializeAsVector3()
  43913. ], FreeCamera.prototype, "ellipsoid", void 0);
  43914. __decorate([
  43915. BABYLON.serializeAsVector3()
  43916. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43917. __decorate([
  43918. BABYLON.serialize()
  43919. ], FreeCamera.prototype, "checkCollisions", void 0);
  43920. __decorate([
  43921. BABYLON.serialize()
  43922. ], FreeCamera.prototype, "applyGravity", void 0);
  43923. return FreeCamera;
  43924. }(BABYLON.TargetCamera));
  43925. BABYLON.FreeCamera = FreeCamera;
  43926. })(BABYLON || (BABYLON = {}));
  43927. //# sourceMappingURL=babylon.freeCamera.js.map
  43928. var BABYLON;
  43929. (function (BABYLON) {
  43930. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43931. function ArcRotateCameraKeyboardMoveInput() {
  43932. this._keys = new Array();
  43933. this.keysUp = [38];
  43934. this.keysDown = [40];
  43935. this.keysLeft = [37];
  43936. this.keysRight = [39];
  43937. this.keysReset = [220];
  43938. this.panningSensibility = 50.0;
  43939. this.zoomingSensibility = 25.0;
  43940. this.useAltToZoom = true;
  43941. }
  43942. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43943. var _this = this;
  43944. if (this._onCanvasBlurObserver) {
  43945. return;
  43946. }
  43947. this._scene = this.camera.getScene();
  43948. this._engine = this._scene.getEngine();
  43949. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43950. _this._keys = [];
  43951. });
  43952. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43953. var evt = info.event;
  43954. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43955. _this._ctrlPressed = evt.ctrlKey;
  43956. _this._altPressed = evt.altKey;
  43957. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43958. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43959. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43960. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43961. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43962. var index = _this._keys.indexOf(evt.keyCode);
  43963. if (index === -1) {
  43964. _this._keys.push(evt.keyCode);
  43965. }
  43966. if (evt.preventDefault) {
  43967. if (!noPreventDefault) {
  43968. evt.preventDefault();
  43969. }
  43970. }
  43971. }
  43972. }
  43973. else {
  43974. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43975. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43976. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43977. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43978. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43979. var index = _this._keys.indexOf(evt.keyCode);
  43980. if (index >= 0) {
  43981. _this._keys.splice(index, 1);
  43982. }
  43983. if (evt.preventDefault) {
  43984. if (!noPreventDefault) {
  43985. evt.preventDefault();
  43986. }
  43987. }
  43988. }
  43989. }
  43990. });
  43991. };
  43992. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43993. if (this._scene) {
  43994. if (this._onKeyboardObserver) {
  43995. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43996. }
  43997. if (this._onCanvasBlurObserver) {
  43998. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43999. }
  44000. this._onKeyboardObserver = null;
  44001. this._onCanvasBlurObserver = null;
  44002. }
  44003. this._keys = [];
  44004. };
  44005. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44006. if (this._onKeyboardObserver) {
  44007. var camera = this.camera;
  44008. for (var index = 0; index < this._keys.length; index++) {
  44009. var keyCode = this._keys[index];
  44010. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44011. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44012. camera.inertialPanningX -= 1 / this.panningSensibility;
  44013. }
  44014. else {
  44015. camera.inertialAlphaOffset -= 0.01;
  44016. }
  44017. }
  44018. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44019. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44020. camera.inertialPanningY += 1 / this.panningSensibility;
  44021. }
  44022. else if (this._altPressed && this.useAltToZoom) {
  44023. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44024. }
  44025. else {
  44026. camera.inertialBetaOffset -= 0.01;
  44027. }
  44028. }
  44029. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44030. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44031. camera.inertialPanningX += 1 / this.panningSensibility;
  44032. }
  44033. else {
  44034. camera.inertialAlphaOffset += 0.01;
  44035. }
  44036. }
  44037. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44038. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44039. camera.inertialPanningY -= 1 / this.panningSensibility;
  44040. }
  44041. else if (this._altPressed && this.useAltToZoom) {
  44042. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44043. }
  44044. else {
  44045. camera.inertialBetaOffset += 0.01;
  44046. }
  44047. }
  44048. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44049. camera.restoreState();
  44050. }
  44051. }
  44052. }
  44053. };
  44054. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44055. return "ArcRotateCameraKeyboardMoveInput";
  44056. };
  44057. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44058. return "keyboard";
  44059. };
  44060. __decorate([
  44061. BABYLON.serialize()
  44062. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44063. __decorate([
  44064. BABYLON.serialize()
  44065. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44066. __decorate([
  44067. BABYLON.serialize()
  44068. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44069. __decorate([
  44070. BABYLON.serialize()
  44071. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44072. __decorate([
  44073. BABYLON.serialize()
  44074. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44075. __decorate([
  44076. BABYLON.serialize()
  44077. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44078. __decorate([
  44079. BABYLON.serialize()
  44080. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44081. __decorate([
  44082. BABYLON.serialize()
  44083. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44084. return ArcRotateCameraKeyboardMoveInput;
  44085. }());
  44086. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44087. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44088. })(BABYLON || (BABYLON = {}));
  44089. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44090. var BABYLON;
  44091. (function (BABYLON) {
  44092. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44093. function ArcRotateCameraMouseWheelInput() {
  44094. this.wheelPrecision = 3.0;
  44095. /**
  44096. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44097. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44098. */
  44099. this.wheelDeltaPercentage = 0;
  44100. }
  44101. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44102. var _this = this;
  44103. this._wheel = function (p, s) {
  44104. //sanity check - this should be a PointerWheel event.
  44105. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44106. return;
  44107. var event = p.event;
  44108. var delta = 0;
  44109. if (event.wheelDelta) {
  44110. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44111. }
  44112. else if (event.detail) {
  44113. delta = -event.detail / _this.wheelPrecision;
  44114. }
  44115. if (delta)
  44116. _this.camera.inertialRadiusOffset += delta;
  44117. if (event.preventDefault) {
  44118. if (!noPreventDefault) {
  44119. event.preventDefault();
  44120. }
  44121. }
  44122. };
  44123. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44124. };
  44125. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44126. if (this._observer && element) {
  44127. this.camera.getScene().onPointerObservable.remove(this._observer);
  44128. this._observer = null;
  44129. this._wheel = null;
  44130. }
  44131. };
  44132. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44133. return "ArcRotateCameraMouseWheelInput";
  44134. };
  44135. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44136. return "mousewheel";
  44137. };
  44138. __decorate([
  44139. BABYLON.serialize()
  44140. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44141. __decorate([
  44142. BABYLON.serialize()
  44143. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44144. return ArcRotateCameraMouseWheelInput;
  44145. }());
  44146. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44147. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44148. })(BABYLON || (BABYLON = {}));
  44149. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44150. var BABYLON;
  44151. (function (BABYLON) {
  44152. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44153. function ArcRotateCameraPointersInput() {
  44154. this.buttons = [0, 1, 2];
  44155. this.angularSensibilityX = 1000.0;
  44156. this.angularSensibilityY = 1000.0;
  44157. this.pinchPrecision = 12.0;
  44158. /**
  44159. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44160. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44161. */
  44162. this.pinchDeltaPercentage = 0;
  44163. this.panningSensibility = 1000.0;
  44164. this.multiTouchPanning = true;
  44165. this.multiTouchPanAndZoom = true;
  44166. this._isPanClick = false;
  44167. this.pinchInwards = true;
  44168. }
  44169. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44170. var _this = this;
  44171. var engine = this.camera.getEngine();
  44172. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44173. var pointA = null;
  44174. var pointB = null;
  44175. var previousPinchSquaredDistance = 0;
  44176. var initialDistance = 0;
  44177. var twoFingerActivityCount = 0;
  44178. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44179. this._pointerInput = function (p, s) {
  44180. var evt = p.event;
  44181. var isTouch = p.event.pointerType === "touch";
  44182. if (engine.isInVRExclusivePointerMode) {
  44183. return;
  44184. }
  44185. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44186. return;
  44187. }
  44188. var srcElement = (evt.srcElement || evt.target);
  44189. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44190. try {
  44191. srcElement.setPointerCapture(evt.pointerId);
  44192. }
  44193. catch (e) {
  44194. //Nothing to do with the error. Execution will continue.
  44195. }
  44196. // Manage panning with pan button click
  44197. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44198. // manage pointers
  44199. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44200. if (pointA === null) {
  44201. pointA = cacheSoloPointer;
  44202. }
  44203. else if (pointB === null) {
  44204. pointB = cacheSoloPointer;
  44205. }
  44206. if (!noPreventDefault) {
  44207. evt.preventDefault();
  44208. element.focus();
  44209. }
  44210. }
  44211. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44212. _this.camera.restoreState();
  44213. }
  44214. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44215. try {
  44216. srcElement.releasePointerCapture(evt.pointerId);
  44217. }
  44218. catch (e) {
  44219. //Nothing to do with the error.
  44220. }
  44221. cacheSoloPointer = null;
  44222. previousPinchSquaredDistance = 0;
  44223. previousMultiTouchPanPosition.isPaning = false;
  44224. previousMultiTouchPanPosition.isPinching = false;
  44225. twoFingerActivityCount = 0;
  44226. initialDistance = 0;
  44227. if (!isTouch) {
  44228. pointB = null; // Mouse and pen are mono pointer
  44229. }
  44230. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44231. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44232. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44233. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44234. if (engine.badOS) {
  44235. pointA = pointB = null;
  44236. }
  44237. else {
  44238. //only remove the impacted pointer in case of multitouch allowing on most
  44239. //platforms switching from rotate to zoom and pan seamlessly.
  44240. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44241. pointA = pointB;
  44242. pointB = null;
  44243. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44244. }
  44245. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44246. pointB = null;
  44247. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44248. }
  44249. else {
  44250. pointA = pointB = null;
  44251. }
  44252. }
  44253. if (!noPreventDefault) {
  44254. evt.preventDefault();
  44255. }
  44256. }
  44257. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44258. if (!noPreventDefault) {
  44259. evt.preventDefault();
  44260. }
  44261. // One button down
  44262. if (pointA && pointB === null && cacheSoloPointer) {
  44263. if (_this.panningSensibility !== 0 &&
  44264. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44265. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44266. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44267. }
  44268. else {
  44269. var offsetX = evt.clientX - cacheSoloPointer.x;
  44270. var offsetY = evt.clientY - cacheSoloPointer.y;
  44271. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44272. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44273. }
  44274. cacheSoloPointer.x = evt.clientX;
  44275. cacheSoloPointer.y = evt.clientY;
  44276. }
  44277. else if (pointA && pointB) {
  44278. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44279. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44280. ed.x = evt.clientX;
  44281. ed.y = evt.clientY;
  44282. var direction = _this.pinchInwards ? 1 : -1;
  44283. var distX = pointA.x - pointB.x;
  44284. var distY = pointA.y - pointB.y;
  44285. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44286. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44287. if (previousPinchSquaredDistance === 0) {
  44288. initialDistance = pinchDistance;
  44289. previousPinchSquaredDistance = pinchSquaredDistance;
  44290. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44291. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44292. return;
  44293. }
  44294. if (_this.multiTouchPanAndZoom) {
  44295. if (_this.pinchDeltaPercentage) {
  44296. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44297. }
  44298. else {
  44299. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44300. (_this.pinchPrecision *
  44301. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44302. direction);
  44303. }
  44304. if (_this.panningSensibility !== 0) {
  44305. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44306. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44307. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44308. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44309. previousMultiTouchPanPosition.x = pointersCenterX;
  44310. previousMultiTouchPanPosition.y = pointersCenterY;
  44311. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44312. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44313. }
  44314. }
  44315. else {
  44316. twoFingerActivityCount++;
  44317. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44318. if (_this.pinchDeltaPercentage) {
  44319. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44320. }
  44321. else {
  44322. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44323. (_this.pinchPrecision *
  44324. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44325. direction);
  44326. }
  44327. previousMultiTouchPanPosition.isPaning = false;
  44328. previousMultiTouchPanPosition.isPinching = true;
  44329. }
  44330. else {
  44331. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44332. if (!previousMultiTouchPanPosition.isPaning) {
  44333. previousMultiTouchPanPosition.isPaning = true;
  44334. previousMultiTouchPanPosition.isPinching = false;
  44335. previousMultiTouchPanPosition.x = ed.x;
  44336. previousMultiTouchPanPosition.y = ed.y;
  44337. return;
  44338. }
  44339. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44340. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44341. }
  44342. }
  44343. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44344. previousMultiTouchPanPosition.x = ed.x;
  44345. previousMultiTouchPanPosition.y = ed.y;
  44346. }
  44347. }
  44348. previousPinchSquaredDistance = pinchSquaredDistance;
  44349. }
  44350. }
  44351. };
  44352. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44353. this._onContextMenu = function (evt) {
  44354. evt.preventDefault();
  44355. };
  44356. if (!this.camera._useCtrlForPanning) {
  44357. element.addEventListener("contextmenu", this._onContextMenu, false);
  44358. }
  44359. this._onLostFocus = function () {
  44360. //this._keys = [];
  44361. pointA = pointB = null;
  44362. previousPinchSquaredDistance = 0;
  44363. previousMultiTouchPanPosition.isPaning = false;
  44364. previousMultiTouchPanPosition.isPinching = false;
  44365. twoFingerActivityCount = 0;
  44366. cacheSoloPointer = null;
  44367. initialDistance = 0;
  44368. };
  44369. this._onMouseMove = function (evt) {
  44370. if (!engine.isPointerLock) {
  44371. return;
  44372. }
  44373. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44374. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44375. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44376. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44377. if (!noPreventDefault) {
  44378. evt.preventDefault();
  44379. }
  44380. };
  44381. this._onGestureStart = function (e) {
  44382. if (window.MSGesture === undefined) {
  44383. return;
  44384. }
  44385. if (!_this._MSGestureHandler) {
  44386. _this._MSGestureHandler = new MSGesture();
  44387. _this._MSGestureHandler.target = element;
  44388. }
  44389. _this._MSGestureHandler.addPointer(e.pointerId);
  44390. };
  44391. this._onGesture = function (e) {
  44392. _this.camera.radius *= e.scale;
  44393. if (e.preventDefault) {
  44394. if (!noPreventDefault) {
  44395. e.stopPropagation();
  44396. e.preventDefault();
  44397. }
  44398. }
  44399. };
  44400. element.addEventListener("mousemove", this._onMouseMove, false);
  44401. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44402. element.addEventListener("MSGestureChange", this._onGesture, false);
  44403. BABYLON.Tools.RegisterTopRootEvents([
  44404. { name: "blur", handler: this._onLostFocus }
  44405. ]);
  44406. };
  44407. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44408. if (this._onLostFocus) {
  44409. BABYLON.Tools.UnregisterTopRootEvents([
  44410. { name: "blur", handler: this._onLostFocus }
  44411. ]);
  44412. }
  44413. if (element && this._observer) {
  44414. this.camera.getScene().onPointerObservable.remove(this._observer);
  44415. this._observer = null;
  44416. if (this._onContextMenu) {
  44417. element.removeEventListener("contextmenu", this._onContextMenu);
  44418. }
  44419. if (this._onMouseMove) {
  44420. element.removeEventListener("mousemove", this._onMouseMove);
  44421. }
  44422. if (this._onGestureStart) {
  44423. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44424. }
  44425. if (this._onGesture) {
  44426. element.removeEventListener("MSGestureChange", this._onGesture);
  44427. }
  44428. this._isPanClick = false;
  44429. this.pinchInwards = true;
  44430. this._onMouseMove = null;
  44431. this._onGestureStart = null;
  44432. this._onGesture = null;
  44433. this._MSGestureHandler = null;
  44434. this._onLostFocus = null;
  44435. this._onContextMenu = null;
  44436. }
  44437. };
  44438. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44439. return "ArcRotateCameraPointersInput";
  44440. };
  44441. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44442. return "pointers";
  44443. };
  44444. __decorate([
  44445. BABYLON.serialize()
  44446. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44447. __decorate([
  44448. BABYLON.serialize()
  44449. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44450. __decorate([
  44451. BABYLON.serialize()
  44452. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44453. __decorate([
  44454. BABYLON.serialize()
  44455. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44456. __decorate([
  44457. BABYLON.serialize()
  44458. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44459. __decorate([
  44460. BABYLON.serialize()
  44461. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44462. __decorate([
  44463. BABYLON.serialize()
  44464. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44465. __decorate([
  44466. BABYLON.serialize()
  44467. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44468. return ArcRotateCameraPointersInput;
  44469. }());
  44470. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44471. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44472. })(BABYLON || (BABYLON = {}));
  44473. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44474. var BABYLON;
  44475. (function (BABYLON) {
  44476. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44477. __extends(ArcRotateCameraInputsManager, _super);
  44478. function ArcRotateCameraInputsManager(camera) {
  44479. return _super.call(this, camera) || this;
  44480. }
  44481. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44482. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44483. return this;
  44484. };
  44485. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44486. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44487. return this;
  44488. };
  44489. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44490. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44491. return this;
  44492. };
  44493. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44494. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44495. return this;
  44496. };
  44497. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44498. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44499. return this;
  44500. };
  44501. return ArcRotateCameraInputsManager;
  44502. }(BABYLON.CameraInputsManager));
  44503. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44504. })(BABYLON || (BABYLON = {}));
  44505. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44506. var BABYLON;
  44507. (function (BABYLON) {
  44508. var ArcRotateCamera = /** @class */ (function (_super) {
  44509. __extends(ArcRotateCamera, _super);
  44510. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44511. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44512. _this.inertialAlphaOffset = 0;
  44513. _this.inertialBetaOffset = 0;
  44514. _this.inertialRadiusOffset = 0;
  44515. _this.lowerAlphaLimit = null;
  44516. _this.upperAlphaLimit = null;
  44517. _this.lowerBetaLimit = 0.01;
  44518. _this.upperBetaLimit = Math.PI;
  44519. _this.lowerRadiusLimit = null;
  44520. _this.upperRadiusLimit = null;
  44521. _this.inertialPanningX = 0;
  44522. _this.inertialPanningY = 0;
  44523. _this.pinchToPanMaxDistance = 20;
  44524. _this.panningDistanceLimit = null;
  44525. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44526. _this.panningInertia = 0.9;
  44527. //-- end properties for backward compatibility for inputs
  44528. _this.zoomOnFactor = 1;
  44529. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44530. _this.allowUpsideDown = true;
  44531. _this._viewMatrix = new BABYLON.Matrix();
  44532. // Panning
  44533. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44534. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44535. _this.checkCollisions = false;
  44536. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44537. _this._previousPosition = BABYLON.Vector3.Zero();
  44538. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44539. _this._newPosition = BABYLON.Vector3.Zero();
  44540. _this._computationVector = BABYLON.Vector3.Zero();
  44541. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44542. if (collidedMesh === void 0) { collidedMesh = null; }
  44543. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44544. newPosition.multiplyInPlace(_this._collider._radius);
  44545. }
  44546. if (!collidedMesh) {
  44547. _this._previousPosition.copyFrom(_this.position);
  44548. }
  44549. else {
  44550. _this.setPosition(newPosition);
  44551. if (_this.onCollide) {
  44552. _this.onCollide(collidedMesh);
  44553. }
  44554. }
  44555. // Recompute because of constraints
  44556. var cosa = Math.cos(_this.alpha);
  44557. var sina = Math.sin(_this.alpha);
  44558. var cosb = Math.cos(_this.beta);
  44559. var sinb = Math.sin(_this.beta);
  44560. if (sinb === 0) {
  44561. sinb = 0.0001;
  44562. }
  44563. var target = _this._getTargetPosition();
  44564. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44565. target.addToRef(_this._computationVector, _this._newPosition);
  44566. _this.position.copyFrom(_this._newPosition);
  44567. var up = _this.upVector;
  44568. if (_this.allowUpsideDown && _this.beta < 0) {
  44569. up = up.clone();
  44570. up = up.negate();
  44571. }
  44572. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44573. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44574. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44575. _this._collisionTriggered = false;
  44576. };
  44577. _this._target = BABYLON.Vector3.Zero();
  44578. if (target) {
  44579. _this.setTarget(target);
  44580. }
  44581. _this.alpha = alpha;
  44582. _this.beta = beta;
  44583. _this.radius = radius;
  44584. _this.getViewMatrix();
  44585. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44586. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44587. return _this;
  44588. }
  44589. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44590. get: function () {
  44591. return this._target;
  44592. },
  44593. set: function (value) {
  44594. this.setTarget(value);
  44595. },
  44596. enumerable: true,
  44597. configurable: true
  44598. });
  44599. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44600. //-- begin properties for backward compatibility for inputs
  44601. get: function () {
  44602. var pointers = this.inputs.attached["pointers"];
  44603. if (pointers)
  44604. return pointers.angularSensibilityX;
  44605. return 0;
  44606. },
  44607. set: function (value) {
  44608. var pointers = this.inputs.attached["pointers"];
  44609. if (pointers) {
  44610. pointers.angularSensibilityX = value;
  44611. }
  44612. },
  44613. enumerable: true,
  44614. configurable: true
  44615. });
  44616. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44617. get: function () {
  44618. var pointers = this.inputs.attached["pointers"];
  44619. if (pointers)
  44620. return pointers.angularSensibilityY;
  44621. return 0;
  44622. },
  44623. set: function (value) {
  44624. var pointers = this.inputs.attached["pointers"];
  44625. if (pointers) {
  44626. pointers.angularSensibilityY = value;
  44627. }
  44628. },
  44629. enumerable: true,
  44630. configurable: true
  44631. });
  44632. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44633. get: function () {
  44634. var pointers = this.inputs.attached["pointers"];
  44635. if (pointers)
  44636. return pointers.pinchPrecision;
  44637. return 0;
  44638. },
  44639. set: function (value) {
  44640. var pointers = this.inputs.attached["pointers"];
  44641. if (pointers) {
  44642. pointers.pinchPrecision = value;
  44643. }
  44644. },
  44645. enumerable: true,
  44646. configurable: true
  44647. });
  44648. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44649. get: function () {
  44650. var pointers = this.inputs.attached["pointers"];
  44651. if (pointers)
  44652. return pointers.pinchDeltaPercentage;
  44653. return 0;
  44654. },
  44655. set: function (value) {
  44656. var pointers = this.inputs.attached["pointers"];
  44657. if (pointers) {
  44658. pointers.pinchDeltaPercentage = value;
  44659. }
  44660. },
  44661. enumerable: true,
  44662. configurable: true
  44663. });
  44664. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44665. get: function () {
  44666. var pointers = this.inputs.attached["pointers"];
  44667. if (pointers)
  44668. return pointers.panningSensibility;
  44669. return 0;
  44670. },
  44671. set: function (value) {
  44672. var pointers = this.inputs.attached["pointers"];
  44673. if (pointers) {
  44674. pointers.panningSensibility = value;
  44675. }
  44676. },
  44677. enumerable: true,
  44678. configurable: true
  44679. });
  44680. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44681. get: function () {
  44682. var keyboard = this.inputs.attached["keyboard"];
  44683. if (keyboard)
  44684. return keyboard.keysUp;
  44685. return [];
  44686. },
  44687. set: function (value) {
  44688. var keyboard = this.inputs.attached["keyboard"];
  44689. if (keyboard)
  44690. keyboard.keysUp = value;
  44691. },
  44692. enumerable: true,
  44693. configurable: true
  44694. });
  44695. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44696. get: function () {
  44697. var keyboard = this.inputs.attached["keyboard"];
  44698. if (keyboard)
  44699. return keyboard.keysDown;
  44700. return [];
  44701. },
  44702. set: function (value) {
  44703. var keyboard = this.inputs.attached["keyboard"];
  44704. if (keyboard)
  44705. keyboard.keysDown = value;
  44706. },
  44707. enumerable: true,
  44708. configurable: true
  44709. });
  44710. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44711. get: function () {
  44712. var keyboard = this.inputs.attached["keyboard"];
  44713. if (keyboard)
  44714. return keyboard.keysLeft;
  44715. return [];
  44716. },
  44717. set: function (value) {
  44718. var keyboard = this.inputs.attached["keyboard"];
  44719. if (keyboard)
  44720. keyboard.keysLeft = value;
  44721. },
  44722. enumerable: true,
  44723. configurable: true
  44724. });
  44725. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44726. get: function () {
  44727. var keyboard = this.inputs.attached["keyboard"];
  44728. if (keyboard)
  44729. return keyboard.keysRight;
  44730. return [];
  44731. },
  44732. set: function (value) {
  44733. var keyboard = this.inputs.attached["keyboard"];
  44734. if (keyboard)
  44735. keyboard.keysRight = value;
  44736. },
  44737. enumerable: true,
  44738. configurable: true
  44739. });
  44740. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44741. get: function () {
  44742. var mousewheel = this.inputs.attached["mousewheel"];
  44743. if (mousewheel)
  44744. return mousewheel.wheelPrecision;
  44745. return 0;
  44746. },
  44747. set: function (value) {
  44748. var mousewheel = this.inputs.attached["mousewheel"];
  44749. if (mousewheel)
  44750. mousewheel.wheelPrecision = value;
  44751. },
  44752. enumerable: true,
  44753. configurable: true
  44754. });
  44755. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44756. get: function () {
  44757. var mousewheel = this.inputs.attached["mousewheel"];
  44758. if (mousewheel)
  44759. return mousewheel.wheelDeltaPercentage;
  44760. return 0;
  44761. },
  44762. set: function (value) {
  44763. var mousewheel = this.inputs.attached["mousewheel"];
  44764. if (mousewheel)
  44765. mousewheel.wheelDeltaPercentage = value;
  44766. },
  44767. enumerable: true,
  44768. configurable: true
  44769. });
  44770. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44771. get: function () {
  44772. return this._bouncingBehavior;
  44773. },
  44774. enumerable: true,
  44775. configurable: true
  44776. });
  44777. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44778. get: function () {
  44779. return this._bouncingBehavior != null;
  44780. },
  44781. set: function (value) {
  44782. if (value === this.useBouncingBehavior) {
  44783. return;
  44784. }
  44785. if (value) {
  44786. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44787. this.addBehavior(this._bouncingBehavior);
  44788. }
  44789. else if (this._bouncingBehavior) {
  44790. this.removeBehavior(this._bouncingBehavior);
  44791. this._bouncingBehavior = null;
  44792. }
  44793. },
  44794. enumerable: true,
  44795. configurable: true
  44796. });
  44797. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44798. get: function () {
  44799. return this._framingBehavior;
  44800. },
  44801. enumerable: true,
  44802. configurable: true
  44803. });
  44804. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44805. get: function () {
  44806. return this._framingBehavior != null;
  44807. },
  44808. set: function (value) {
  44809. if (value === this.useFramingBehavior) {
  44810. return;
  44811. }
  44812. if (value) {
  44813. this._framingBehavior = new BABYLON.FramingBehavior();
  44814. this.addBehavior(this._framingBehavior);
  44815. }
  44816. else if (this._framingBehavior) {
  44817. this.removeBehavior(this._framingBehavior);
  44818. this._framingBehavior = null;
  44819. }
  44820. },
  44821. enumerable: true,
  44822. configurable: true
  44823. });
  44824. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44825. get: function () {
  44826. return this._autoRotationBehavior;
  44827. },
  44828. enumerable: true,
  44829. configurable: true
  44830. });
  44831. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44832. get: function () {
  44833. return this._autoRotationBehavior != null;
  44834. },
  44835. set: function (value) {
  44836. if (value === this.useAutoRotationBehavior) {
  44837. return;
  44838. }
  44839. if (value) {
  44840. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44841. this.addBehavior(this._autoRotationBehavior);
  44842. }
  44843. else if (this._autoRotationBehavior) {
  44844. this.removeBehavior(this._autoRotationBehavior);
  44845. this._autoRotationBehavior = null;
  44846. }
  44847. },
  44848. enumerable: true,
  44849. configurable: true
  44850. });
  44851. // Cache
  44852. ArcRotateCamera.prototype._initCache = function () {
  44853. _super.prototype._initCache.call(this);
  44854. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44855. this._cache.alpha = undefined;
  44856. this._cache.beta = undefined;
  44857. this._cache.radius = undefined;
  44858. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44859. };
  44860. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44861. if (!ignoreParentClass) {
  44862. _super.prototype._updateCache.call(this);
  44863. }
  44864. this._cache._target.copyFrom(this._getTargetPosition());
  44865. this._cache.alpha = this.alpha;
  44866. this._cache.beta = this.beta;
  44867. this._cache.radius = this.radius;
  44868. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44869. };
  44870. ArcRotateCamera.prototype._getTargetPosition = function () {
  44871. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44872. var pos = this._targetHost.getAbsolutePosition();
  44873. if (this._targetBoundingCenter) {
  44874. pos.addToRef(this._targetBoundingCenter, this._target);
  44875. }
  44876. else {
  44877. this._target.copyFrom(pos);
  44878. }
  44879. }
  44880. var lockedTargetPosition = this._getLockedTargetPosition();
  44881. if (lockedTargetPosition) {
  44882. return lockedTargetPosition;
  44883. }
  44884. return this._target;
  44885. };
  44886. ArcRotateCamera.prototype.storeState = function () {
  44887. this._storedAlpha = this.alpha;
  44888. this._storedBeta = this.beta;
  44889. this._storedRadius = this.radius;
  44890. this._storedTarget = this._getTargetPosition().clone();
  44891. return _super.prototype.storeState.call(this);
  44892. };
  44893. /**
  44894. * Restored camera state. You must call storeState() first
  44895. */
  44896. ArcRotateCamera.prototype._restoreStateValues = function () {
  44897. if (!_super.prototype._restoreStateValues.call(this)) {
  44898. return false;
  44899. }
  44900. this.alpha = this._storedAlpha;
  44901. this.beta = this._storedBeta;
  44902. this.radius = this._storedRadius;
  44903. this.setTarget(this._storedTarget.clone());
  44904. this.inertialAlphaOffset = 0;
  44905. this.inertialBetaOffset = 0;
  44906. this.inertialRadiusOffset = 0;
  44907. this.inertialPanningX = 0;
  44908. this.inertialPanningY = 0;
  44909. return true;
  44910. };
  44911. // Synchronized
  44912. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44913. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44914. return false;
  44915. return this._cache._target.equals(this._getTargetPosition())
  44916. && this._cache.alpha === this.alpha
  44917. && this._cache.beta === this.beta
  44918. && this._cache.radius === this.radius
  44919. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44920. };
  44921. // Methods
  44922. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44923. var _this = this;
  44924. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44925. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44926. this._useCtrlForPanning = useCtrlForPanning;
  44927. this._panningMouseButton = panningMouseButton;
  44928. this.inputs.attachElement(element, noPreventDefault);
  44929. this._reset = function () {
  44930. _this.inertialAlphaOffset = 0;
  44931. _this.inertialBetaOffset = 0;
  44932. _this.inertialRadiusOffset = 0;
  44933. _this.inertialPanningX = 0;
  44934. _this.inertialPanningY = 0;
  44935. };
  44936. };
  44937. ArcRotateCamera.prototype.detachControl = function (element) {
  44938. this.inputs.detachElement(element);
  44939. if (this._reset) {
  44940. this._reset();
  44941. }
  44942. };
  44943. ArcRotateCamera.prototype._checkInputs = function () {
  44944. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44945. if (this._collisionTriggered) {
  44946. return;
  44947. }
  44948. this.inputs.checkInputs();
  44949. // Inertia
  44950. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44951. if (this.getScene().useRightHandedSystem) {
  44952. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44953. }
  44954. else {
  44955. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44956. }
  44957. this.beta += this.inertialBetaOffset;
  44958. this.radius -= this.inertialRadiusOffset;
  44959. this.inertialAlphaOffset *= this.inertia;
  44960. this.inertialBetaOffset *= this.inertia;
  44961. this.inertialRadiusOffset *= this.inertia;
  44962. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44963. this.inertialAlphaOffset = 0;
  44964. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44965. this.inertialBetaOffset = 0;
  44966. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44967. this.inertialRadiusOffset = 0;
  44968. }
  44969. // Panning inertia
  44970. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44971. if (!this._localDirection) {
  44972. this._localDirection = BABYLON.Vector3.Zero();
  44973. this._transformedDirection = BABYLON.Vector3.Zero();
  44974. }
  44975. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44976. this._localDirection.multiplyInPlace(this.panningAxis);
  44977. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44978. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44979. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44980. if (!this.panningAxis.y) {
  44981. this._transformedDirection.y = 0;
  44982. }
  44983. if (!this._targetHost) {
  44984. if (this.panningDistanceLimit) {
  44985. this._transformedDirection.addInPlace(this._target);
  44986. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44987. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44988. this._target.copyFrom(this._transformedDirection);
  44989. }
  44990. }
  44991. else {
  44992. this._target.addInPlace(this._transformedDirection);
  44993. }
  44994. }
  44995. this.inertialPanningX *= this.panningInertia;
  44996. this.inertialPanningY *= this.panningInertia;
  44997. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44998. this.inertialPanningX = 0;
  44999. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45000. this.inertialPanningY = 0;
  45001. }
  45002. // Limits
  45003. this._checkLimits();
  45004. _super.prototype._checkInputs.call(this);
  45005. };
  45006. ArcRotateCamera.prototype._checkLimits = function () {
  45007. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45008. if (this.allowUpsideDown && this.beta > Math.PI) {
  45009. this.beta = this.beta - (2 * Math.PI);
  45010. }
  45011. }
  45012. else {
  45013. if (this.beta < this.lowerBetaLimit) {
  45014. this.beta = this.lowerBetaLimit;
  45015. }
  45016. }
  45017. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45018. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45019. this.beta = this.beta + (2 * Math.PI);
  45020. }
  45021. }
  45022. else {
  45023. if (this.beta > this.upperBetaLimit) {
  45024. this.beta = this.upperBetaLimit;
  45025. }
  45026. }
  45027. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45028. this.alpha = this.lowerAlphaLimit;
  45029. }
  45030. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45031. this.alpha = this.upperAlphaLimit;
  45032. }
  45033. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45034. this.radius = this.lowerRadiusLimit;
  45035. }
  45036. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45037. this.radius = this.upperRadiusLimit;
  45038. }
  45039. };
  45040. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45041. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45042. this.radius = this._computationVector.length();
  45043. if (this.radius === 0) {
  45044. this.radius = 0.0001; // Just to avoid division by zero
  45045. }
  45046. // Alpha
  45047. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45048. if (this._computationVector.z < 0) {
  45049. this.alpha = 2 * Math.PI - this.alpha;
  45050. }
  45051. // Beta
  45052. this.beta = Math.acos(this._computationVector.y / this.radius);
  45053. this._checkLimits();
  45054. };
  45055. ArcRotateCamera.prototype.setPosition = function (position) {
  45056. if (this.position.equals(position)) {
  45057. return;
  45058. }
  45059. this.position.copyFrom(position);
  45060. this.rebuildAnglesAndRadius();
  45061. };
  45062. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45063. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45064. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45065. if (target.getBoundingInfo) {
  45066. if (toBoundingCenter) {
  45067. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45068. }
  45069. else {
  45070. this._targetBoundingCenter = null;
  45071. }
  45072. this._targetHost = target;
  45073. this._target = this._getTargetPosition();
  45074. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45075. }
  45076. else {
  45077. var newTarget = target;
  45078. var currentTarget = this._getTargetPosition();
  45079. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45080. return;
  45081. }
  45082. this._targetHost = null;
  45083. this._target = newTarget;
  45084. this._targetBoundingCenter = null;
  45085. this.onMeshTargetChangedObservable.notifyObservers(null);
  45086. }
  45087. this.rebuildAnglesAndRadius();
  45088. };
  45089. ArcRotateCamera.prototype._getViewMatrix = function () {
  45090. // Compute
  45091. var cosa = Math.cos(this.alpha);
  45092. var sina = Math.sin(this.alpha);
  45093. var cosb = Math.cos(this.beta);
  45094. var sinb = Math.sin(this.beta);
  45095. if (sinb === 0) {
  45096. sinb = 0.0001;
  45097. }
  45098. var target = this._getTargetPosition();
  45099. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45100. target.addToRef(this._computationVector, this._newPosition);
  45101. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45102. if (!this._collider) {
  45103. this._collider = new BABYLON.Collider();
  45104. }
  45105. this._collider._radius = this.collisionRadius;
  45106. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45107. this._collisionTriggered = true;
  45108. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45109. }
  45110. else {
  45111. this.position.copyFrom(this._newPosition);
  45112. var up = this.upVector;
  45113. if (this.allowUpsideDown && sinb < 0) {
  45114. up = up.clone();
  45115. up = up.negate();
  45116. }
  45117. if (this.getScene().useRightHandedSystem) {
  45118. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45119. }
  45120. else {
  45121. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45122. }
  45123. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45124. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45125. }
  45126. this._currentTarget = target;
  45127. return this._viewMatrix;
  45128. };
  45129. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45130. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45131. meshes = meshes || this.getScene().meshes;
  45132. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45133. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45134. this.radius = distance * this.zoomOnFactor;
  45135. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45136. };
  45137. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45138. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45139. var meshesOrMinMaxVector;
  45140. var distance;
  45141. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45142. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45143. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45144. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45145. }
  45146. else {
  45147. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45148. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45149. distance = minMaxVectorAndDistance.distance;
  45150. }
  45151. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45152. if (!doNotUpdateMaxZ) {
  45153. this.maxZ = distance * 2;
  45154. }
  45155. };
  45156. /**
  45157. * @override
  45158. * Override Camera.createRigCamera
  45159. */
  45160. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45161. var alphaShift = 0;
  45162. switch (this.cameraRigMode) {
  45163. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45164. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45165. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45166. case BABYLON.Camera.RIG_MODE_VR:
  45167. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45168. break;
  45169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45170. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45171. break;
  45172. }
  45173. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45174. rigCam._cameraRigParams = {};
  45175. return rigCam;
  45176. };
  45177. /**
  45178. * @override
  45179. * Override Camera._updateRigCameras
  45180. */
  45181. ArcRotateCamera.prototype._updateRigCameras = function () {
  45182. var camLeft = this._rigCameras[0];
  45183. var camRight = this._rigCameras[1];
  45184. camLeft.beta = camRight.beta = this.beta;
  45185. camLeft.radius = camRight.radius = this.radius;
  45186. switch (this.cameraRigMode) {
  45187. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45190. case BABYLON.Camera.RIG_MODE_VR:
  45191. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45192. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45193. break;
  45194. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45195. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45196. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45197. break;
  45198. }
  45199. _super.prototype._updateRigCameras.call(this);
  45200. };
  45201. ArcRotateCamera.prototype.dispose = function () {
  45202. this.inputs.clear();
  45203. _super.prototype.dispose.call(this);
  45204. };
  45205. ArcRotateCamera.prototype.getClassName = function () {
  45206. return "ArcRotateCamera";
  45207. };
  45208. __decorate([
  45209. BABYLON.serialize()
  45210. ], ArcRotateCamera.prototype, "alpha", void 0);
  45211. __decorate([
  45212. BABYLON.serialize()
  45213. ], ArcRotateCamera.prototype, "beta", void 0);
  45214. __decorate([
  45215. BABYLON.serialize()
  45216. ], ArcRotateCamera.prototype, "radius", void 0);
  45217. __decorate([
  45218. BABYLON.serializeAsVector3("target")
  45219. ], ArcRotateCamera.prototype, "_target", void 0);
  45220. __decorate([
  45221. BABYLON.serialize()
  45222. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45223. __decorate([
  45224. BABYLON.serialize()
  45225. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45226. __decorate([
  45227. BABYLON.serialize()
  45228. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45229. __decorate([
  45230. BABYLON.serialize()
  45231. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45232. __decorate([
  45233. BABYLON.serialize()
  45234. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45235. __decorate([
  45236. BABYLON.serialize()
  45237. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45238. __decorate([
  45239. BABYLON.serialize()
  45240. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45241. __decorate([
  45242. BABYLON.serialize()
  45243. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45244. __decorate([
  45245. BABYLON.serialize()
  45246. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45247. __decorate([
  45248. BABYLON.serialize()
  45249. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45250. __decorate([
  45251. BABYLON.serialize()
  45252. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45253. __decorate([
  45254. BABYLON.serialize()
  45255. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45256. __decorate([
  45257. BABYLON.serialize()
  45258. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45259. __decorate([
  45260. BABYLON.serializeAsVector3()
  45261. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45262. __decorate([
  45263. BABYLON.serialize()
  45264. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45265. __decorate([
  45266. BABYLON.serialize()
  45267. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45268. __decorate([
  45269. BABYLON.serialize()
  45270. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45271. return ArcRotateCamera;
  45272. }(BABYLON.TargetCamera));
  45273. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45274. })(BABYLON || (BABYLON = {}));
  45275. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45276. var BABYLON;
  45277. (function (BABYLON) {
  45278. /**
  45279. * The HemisphericLight simulates the ambient environment light,
  45280. * so the passed direction is the light reflection direction, not the incoming direction.
  45281. */
  45282. var HemisphericLight = /** @class */ (function (_super) {
  45283. __extends(HemisphericLight, _super);
  45284. /**
  45285. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45286. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45287. * The HemisphericLight can't cast shadows.
  45288. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45289. * @param name The friendly name of the light
  45290. * @param direction The direction of the light reflection
  45291. * @param scene The scene the light belongs to
  45292. */
  45293. function HemisphericLight(name, direction, scene) {
  45294. var _this = _super.call(this, name, scene) || this;
  45295. /**
  45296. * The groundColor is the light in the opposite direction to the one specified during creation.
  45297. * 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.
  45298. */
  45299. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45300. _this.direction = direction || BABYLON.Vector3.Up();
  45301. return _this;
  45302. }
  45303. HemisphericLight.prototype._buildUniformLayout = function () {
  45304. this._uniformBuffer.addUniform("vLightData", 4);
  45305. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45306. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45307. this._uniformBuffer.addUniform("vLightGround", 3);
  45308. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45309. this._uniformBuffer.addUniform("depthValues", 2);
  45310. this._uniformBuffer.create();
  45311. };
  45312. /**
  45313. * Returns the string "HemisphericLight".
  45314. * @return The class name
  45315. */
  45316. HemisphericLight.prototype.getClassName = function () {
  45317. return "HemisphericLight";
  45318. };
  45319. /**
  45320. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45321. * Returns the updated direction.
  45322. * @param target The target the direction should point to
  45323. * @return The computed direction
  45324. */
  45325. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45326. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45327. return this.direction;
  45328. };
  45329. /**
  45330. * Returns the shadow generator associated to the light.
  45331. * @returns Always null for hemispheric lights because it does not support shadows.
  45332. */
  45333. HemisphericLight.prototype.getShadowGenerator = function () {
  45334. return null;
  45335. };
  45336. /**
  45337. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45338. * @param effect The effect to update
  45339. * @param lightIndex The index of the light in the effect to update
  45340. * @returns The hemispheric light
  45341. */
  45342. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45343. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45344. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45345. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45346. return this;
  45347. };
  45348. /**
  45349. * @ignore internal use only.
  45350. */
  45351. HemisphericLight.prototype._getWorldMatrix = function () {
  45352. if (!this._worldMatrix) {
  45353. this._worldMatrix = BABYLON.Matrix.Identity();
  45354. }
  45355. return this._worldMatrix;
  45356. };
  45357. /**
  45358. * Returns the integer 3.
  45359. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45360. */
  45361. HemisphericLight.prototype.getTypeID = function () {
  45362. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45363. };
  45364. __decorate([
  45365. BABYLON.serializeAsColor3()
  45366. ], HemisphericLight.prototype, "groundColor", void 0);
  45367. __decorate([
  45368. BABYLON.serializeAsVector3()
  45369. ], HemisphericLight.prototype, "direction", void 0);
  45370. return HemisphericLight;
  45371. }(BABYLON.Light));
  45372. BABYLON.HemisphericLight = HemisphericLight;
  45373. })(BABYLON || (BABYLON = {}));
  45374. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45375. var BABYLON;
  45376. (function (BABYLON) {
  45377. /**
  45378. * Base implementation of @see IShadowLight
  45379. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45380. */
  45381. var ShadowLight = /** @class */ (function (_super) {
  45382. __extends(ShadowLight, _super);
  45383. function ShadowLight() {
  45384. var _this = _super !== null && _super.apply(this, arguments) || this;
  45385. _this._needProjectionMatrixCompute = true;
  45386. return _this;
  45387. }
  45388. ShadowLight.prototype._setPosition = function (value) {
  45389. this._position = value;
  45390. };
  45391. Object.defineProperty(ShadowLight.prototype, "position", {
  45392. /**
  45393. * Sets the position the shadow will be casted from. Also use as the light position for both
  45394. * point and spot lights.
  45395. */
  45396. get: function () {
  45397. return this._position;
  45398. },
  45399. /**
  45400. * Sets the position the shadow will be casted from. Also use as the light position for both
  45401. * point and spot lights.
  45402. */
  45403. set: function (value) {
  45404. this._setPosition(value);
  45405. },
  45406. enumerable: true,
  45407. configurable: true
  45408. });
  45409. ShadowLight.prototype._setDirection = function (value) {
  45410. this._direction = value;
  45411. };
  45412. Object.defineProperty(ShadowLight.prototype, "direction", {
  45413. /**
  45414. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45415. * Also use as the light direction on spot and directional lights.
  45416. */
  45417. get: function () {
  45418. return this._direction;
  45419. },
  45420. /**
  45421. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45422. * Also use as the light direction on spot and directional lights.
  45423. */
  45424. set: function (value) {
  45425. this._setDirection(value);
  45426. },
  45427. enumerable: true,
  45428. configurable: true
  45429. });
  45430. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45431. /**
  45432. * Gets the shadow projection clipping minimum z value.
  45433. */
  45434. get: function () {
  45435. return this._shadowMinZ;
  45436. },
  45437. /**
  45438. * Sets the shadow projection clipping minimum z value.
  45439. */
  45440. set: function (value) {
  45441. this._shadowMinZ = value;
  45442. this.forceProjectionMatrixCompute();
  45443. },
  45444. enumerable: true,
  45445. configurable: true
  45446. });
  45447. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45448. /**
  45449. * Sets the shadow projection clipping maximum z value.
  45450. */
  45451. get: function () {
  45452. return this._shadowMaxZ;
  45453. },
  45454. /**
  45455. * Gets the shadow projection clipping maximum z value.
  45456. */
  45457. set: function (value) {
  45458. this._shadowMaxZ = value;
  45459. this.forceProjectionMatrixCompute();
  45460. },
  45461. enumerable: true,
  45462. configurable: true
  45463. });
  45464. /**
  45465. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45466. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45467. */
  45468. ShadowLight.prototype.computeTransformedInformation = function () {
  45469. if (this.parent && this.parent.getWorldMatrix) {
  45470. if (!this.transformedPosition) {
  45471. this.transformedPosition = BABYLON.Vector3.Zero();
  45472. }
  45473. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45474. // In case the direction is present.
  45475. if (this.direction) {
  45476. if (!this.transformedDirection) {
  45477. this.transformedDirection = BABYLON.Vector3.Zero();
  45478. }
  45479. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45480. }
  45481. return true;
  45482. }
  45483. return false;
  45484. };
  45485. /**
  45486. * Return the depth scale used for the shadow map.
  45487. * @returns the depth scale.
  45488. */
  45489. ShadowLight.prototype.getDepthScale = function () {
  45490. return 50.0;
  45491. };
  45492. /**
  45493. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45494. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45495. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45496. */
  45497. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45498. return this.transformedDirection ? this.transformedDirection : this.direction;
  45499. };
  45500. /**
  45501. * Returns the ShadowLight absolute position in the World.
  45502. * @returns the position vector in world space
  45503. */
  45504. ShadowLight.prototype.getAbsolutePosition = function () {
  45505. return this.transformedPosition ? this.transformedPosition : this.position;
  45506. };
  45507. /**
  45508. * Sets the ShadowLight direction toward the passed target.
  45509. * @param target The point tot target in local space
  45510. * @returns the updated ShadowLight direction
  45511. */
  45512. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45513. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45514. return this.direction;
  45515. };
  45516. /**
  45517. * Returns the light rotation in euler definition.
  45518. * @returns the x y z rotation in local space.
  45519. */
  45520. ShadowLight.prototype.getRotation = function () {
  45521. this.direction.normalize();
  45522. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45523. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45524. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45525. };
  45526. /**
  45527. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45528. * @returns true if a cube texture needs to be use
  45529. */
  45530. ShadowLight.prototype.needCube = function () {
  45531. return false;
  45532. };
  45533. /**
  45534. * Detects if the projection matrix requires to be recomputed this frame.
  45535. * @returns true if it requires to be recomputed otherwise, false.
  45536. */
  45537. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45538. return this._needProjectionMatrixCompute;
  45539. };
  45540. /**
  45541. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45542. */
  45543. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45544. this._needProjectionMatrixCompute = true;
  45545. };
  45546. /**
  45547. * Get the world matrix of the sahdow lights.
  45548. * @ignore Internal Use Only
  45549. */
  45550. ShadowLight.prototype._getWorldMatrix = function () {
  45551. if (!this._worldMatrix) {
  45552. this._worldMatrix = BABYLON.Matrix.Identity();
  45553. }
  45554. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45555. return this._worldMatrix;
  45556. };
  45557. /**
  45558. * Gets the minZ used for shadow according to both the scene and the light.
  45559. * @param activeCamera The camera we are returning the min for
  45560. * @returns the depth min z
  45561. */
  45562. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45563. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45564. };
  45565. /**
  45566. * Gets the maxZ used for shadow according to both the scene and the light.
  45567. * @param activeCamera The camera we are returning the max for
  45568. * @returns the depth max z
  45569. */
  45570. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45571. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45572. };
  45573. /**
  45574. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45575. * @param matrix The materix to updated with the projection information
  45576. * @param viewMatrix The transform matrix of the light
  45577. * @param renderList The list of mesh to render in the map
  45578. * @returns The current light
  45579. */
  45580. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45581. if (this.customProjectionMatrixBuilder) {
  45582. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45583. }
  45584. else {
  45585. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45586. }
  45587. return this;
  45588. };
  45589. __decorate([
  45590. BABYLON.serializeAsVector3()
  45591. ], ShadowLight.prototype, "position", null);
  45592. __decorate([
  45593. BABYLON.serializeAsVector3()
  45594. ], ShadowLight.prototype, "direction", null);
  45595. __decorate([
  45596. BABYLON.serialize()
  45597. ], ShadowLight.prototype, "shadowMinZ", null);
  45598. __decorate([
  45599. BABYLON.serialize()
  45600. ], ShadowLight.prototype, "shadowMaxZ", null);
  45601. return ShadowLight;
  45602. }(BABYLON.Light));
  45603. BABYLON.ShadowLight = ShadowLight;
  45604. })(BABYLON || (BABYLON = {}));
  45605. //# sourceMappingURL=babylon.shadowLight.js.map
  45606. var BABYLON;
  45607. (function (BABYLON) {
  45608. /**
  45609. * A point light is a light defined by an unique point in world space.
  45610. * The light is emitted in every direction from this point.
  45611. * A good example of a point light is a standard light bulb.
  45612. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45613. */
  45614. var PointLight = /** @class */ (function (_super) {
  45615. __extends(PointLight, _super);
  45616. /**
  45617. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45618. * A PointLight emits the light in every direction.
  45619. * It can cast shadows.
  45620. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45621. * ```javascript
  45622. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45623. * ```
  45624. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45625. * @param name The light friendly name
  45626. * @param position The position of the point light in the scene
  45627. * @param scene The scene the lights belongs to
  45628. */
  45629. function PointLight(name, position, scene) {
  45630. var _this = _super.call(this, name, scene) || this;
  45631. _this._shadowAngle = Math.PI / 2;
  45632. _this.position = position;
  45633. return _this;
  45634. }
  45635. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45636. /**
  45637. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45638. * This specifies what angle the shadow will use to be created.
  45639. *
  45640. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45641. */
  45642. get: function () {
  45643. return this._shadowAngle;
  45644. },
  45645. /**
  45646. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45647. * This specifies what angle the shadow will use to be created.
  45648. *
  45649. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45650. */
  45651. set: function (value) {
  45652. this._shadowAngle = value;
  45653. this.forceProjectionMatrixCompute();
  45654. },
  45655. enumerable: true,
  45656. configurable: true
  45657. });
  45658. Object.defineProperty(PointLight.prototype, "direction", {
  45659. /**
  45660. * Gets the direction if it has been set.
  45661. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45662. */
  45663. get: function () {
  45664. return this._direction;
  45665. },
  45666. /**
  45667. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45668. */
  45669. set: function (value) {
  45670. var previousNeedCube = this.needCube();
  45671. this._direction = value;
  45672. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45673. this._shadowGenerator.recreateShadowMap();
  45674. }
  45675. },
  45676. enumerable: true,
  45677. configurable: true
  45678. });
  45679. /**
  45680. * Returns the string "PointLight"
  45681. * @returns the class name
  45682. */
  45683. PointLight.prototype.getClassName = function () {
  45684. return "PointLight";
  45685. };
  45686. /**
  45687. * Returns the integer 0.
  45688. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45689. */
  45690. PointLight.prototype.getTypeID = function () {
  45691. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45692. };
  45693. /**
  45694. * Specifies wether or not the shadowmap should be a cube texture.
  45695. * @returns true if the shadowmap needs to be a cube texture.
  45696. */
  45697. PointLight.prototype.needCube = function () {
  45698. return !this.direction;
  45699. };
  45700. /**
  45701. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45702. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45703. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45704. */
  45705. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45706. if (this.direction) {
  45707. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45708. }
  45709. else {
  45710. switch (faceIndex) {
  45711. case 0:
  45712. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45713. case 1:
  45714. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45715. case 2:
  45716. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45717. case 3:
  45718. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45719. case 4:
  45720. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45721. case 5:
  45722. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45723. }
  45724. }
  45725. return BABYLON.Vector3.Zero();
  45726. };
  45727. /**
  45728. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45729. * - fov = PI / 2
  45730. * - aspect ratio : 1.0
  45731. * - z-near and far equal to the active camera minZ and maxZ.
  45732. * Returns the PointLight.
  45733. */
  45734. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45735. var activeCamera = this.getScene().activeCamera;
  45736. if (!activeCamera) {
  45737. return;
  45738. }
  45739. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45740. };
  45741. PointLight.prototype._buildUniformLayout = function () {
  45742. this._uniformBuffer.addUniform("vLightData", 4);
  45743. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45744. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45745. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45746. this._uniformBuffer.addUniform("depthValues", 2);
  45747. this._uniformBuffer.create();
  45748. };
  45749. /**
  45750. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45751. * @param effect The effect to update
  45752. * @param lightIndex The index of the light in the effect to update
  45753. * @returns The point light
  45754. */
  45755. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45756. if (this.computeTransformedInformation()) {
  45757. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45758. return this;
  45759. }
  45760. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45761. return this;
  45762. };
  45763. __decorate([
  45764. BABYLON.serialize()
  45765. ], PointLight.prototype, "shadowAngle", null);
  45766. return PointLight;
  45767. }(BABYLON.ShadowLight));
  45768. BABYLON.PointLight = PointLight;
  45769. })(BABYLON || (BABYLON = {}));
  45770. //# sourceMappingURL=babylon.pointLight.js.map
  45771. var BABYLON;
  45772. (function (BABYLON) {
  45773. /**
  45774. * A directional light is defined by a direction (what a surprise!).
  45775. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45776. * 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.
  45777. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45778. */
  45779. var DirectionalLight = /** @class */ (function (_super) {
  45780. __extends(DirectionalLight, _super);
  45781. /**
  45782. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45783. * The directional light is emitted from everywhere in the given direction.
  45784. * It can cast shawdows.
  45785. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45786. * @param name The friendly name of the light
  45787. * @param direction The direction of the light
  45788. * @param scene The scene the light belongs to
  45789. */
  45790. function DirectionalLight(name, direction, scene) {
  45791. var _this = _super.call(this, name, scene) || this;
  45792. _this._shadowFrustumSize = 0;
  45793. _this._shadowOrthoScale = 0.5;
  45794. /**
  45795. * Automatically compute the projection matrix to best fit (including all the casters)
  45796. * on each frame.
  45797. */
  45798. _this.autoUpdateExtends = true;
  45799. // Cache
  45800. _this._orthoLeft = Number.MAX_VALUE;
  45801. _this._orthoRight = Number.MIN_VALUE;
  45802. _this._orthoTop = Number.MIN_VALUE;
  45803. _this._orthoBottom = Number.MAX_VALUE;
  45804. _this.position = direction.scale(-1.0);
  45805. _this.direction = direction;
  45806. return _this;
  45807. }
  45808. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45809. /**
  45810. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45811. */
  45812. get: function () {
  45813. return this._shadowFrustumSize;
  45814. },
  45815. /**
  45816. * Specifies a fix frustum size for the shadow generation.
  45817. */
  45818. set: function (value) {
  45819. this._shadowFrustumSize = value;
  45820. this.forceProjectionMatrixCompute();
  45821. },
  45822. enumerable: true,
  45823. configurable: true
  45824. });
  45825. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45826. /**
  45827. * Gets the shadow projection scale against the optimal computed one.
  45828. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45829. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45830. */
  45831. get: function () {
  45832. return this._shadowOrthoScale;
  45833. },
  45834. /**
  45835. * Sets the shadow projection scale against the optimal computed one.
  45836. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45837. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45838. */
  45839. set: function (value) {
  45840. this._shadowOrthoScale = value;
  45841. this.forceProjectionMatrixCompute();
  45842. },
  45843. enumerable: true,
  45844. configurable: true
  45845. });
  45846. /**
  45847. * Returns the string "DirectionalLight".
  45848. * @return The class name
  45849. */
  45850. DirectionalLight.prototype.getClassName = function () {
  45851. return "DirectionalLight";
  45852. };
  45853. /**
  45854. * Returns the integer 1.
  45855. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45856. */
  45857. DirectionalLight.prototype.getTypeID = function () {
  45858. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45859. };
  45860. /**
  45861. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45862. * Returns the DirectionalLight Shadow projection matrix.
  45863. */
  45864. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45865. if (this.shadowFrustumSize > 0) {
  45866. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45867. }
  45868. else {
  45869. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45870. }
  45871. };
  45872. /**
  45873. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45874. * Returns the DirectionalLight Shadow projection matrix.
  45875. */
  45876. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45877. var activeCamera = this.getScene().activeCamera;
  45878. if (!activeCamera) {
  45879. return;
  45880. }
  45881. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45882. };
  45883. /**
  45884. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45885. * Returns the DirectionalLight Shadow projection matrix.
  45886. */
  45887. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45888. var activeCamera = this.getScene().activeCamera;
  45889. if (!activeCamera) {
  45890. return;
  45891. }
  45892. // Check extends
  45893. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45894. var tempVector3 = BABYLON.Vector3.Zero();
  45895. this._orthoLeft = Number.MAX_VALUE;
  45896. this._orthoRight = Number.MIN_VALUE;
  45897. this._orthoTop = Number.MIN_VALUE;
  45898. this._orthoBottom = Number.MAX_VALUE;
  45899. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45900. var mesh = renderList[meshIndex];
  45901. if (!mesh) {
  45902. continue;
  45903. }
  45904. var boundingInfo = mesh.getBoundingInfo();
  45905. var boundingBox = boundingInfo.boundingBox;
  45906. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45907. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45908. if (tempVector3.x < this._orthoLeft)
  45909. this._orthoLeft = tempVector3.x;
  45910. if (tempVector3.y < this._orthoBottom)
  45911. this._orthoBottom = tempVector3.y;
  45912. if (tempVector3.x > this._orthoRight)
  45913. this._orthoRight = tempVector3.x;
  45914. if (tempVector3.y > this._orthoTop)
  45915. this._orthoTop = tempVector3.y;
  45916. }
  45917. }
  45918. }
  45919. var xOffset = this._orthoRight - this._orthoLeft;
  45920. var yOffset = this._orthoTop - this._orthoBottom;
  45921. 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);
  45922. };
  45923. DirectionalLight.prototype._buildUniformLayout = function () {
  45924. this._uniformBuffer.addUniform("vLightData", 4);
  45925. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45926. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45927. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45928. this._uniformBuffer.addUniform("depthValues", 2);
  45929. this._uniformBuffer.create();
  45930. };
  45931. /**
  45932. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45933. * @param effect The effect to update
  45934. * @param lightIndex The index of the light in the effect to update
  45935. * @returns The directional light
  45936. */
  45937. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45938. if (this.computeTransformedInformation()) {
  45939. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45940. return this;
  45941. }
  45942. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45943. return this;
  45944. };
  45945. /**
  45946. * Gets the minZ used for shadow according to both the scene and the light.
  45947. *
  45948. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45949. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45950. * @param activeCamera The camera we are returning the min for
  45951. * @returns the depth min z
  45952. */
  45953. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45954. return 1;
  45955. };
  45956. /**
  45957. * Gets the maxZ used for shadow according to both the scene and the light.
  45958. *
  45959. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45960. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45961. * @param activeCamera The camera we are returning the max for
  45962. * @returns the depth max z
  45963. */
  45964. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45965. return 1;
  45966. };
  45967. __decorate([
  45968. BABYLON.serialize()
  45969. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45970. __decorate([
  45971. BABYLON.serialize()
  45972. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45973. __decorate([
  45974. BABYLON.serialize()
  45975. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45976. return DirectionalLight;
  45977. }(BABYLON.ShadowLight));
  45978. BABYLON.DirectionalLight = DirectionalLight;
  45979. })(BABYLON || (BABYLON = {}));
  45980. //# sourceMappingURL=babylon.directionalLight.js.map
  45981. var BABYLON;
  45982. (function (BABYLON) {
  45983. /**
  45984. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45985. * These values define a cone of light starting from the position, emitting toward the direction.
  45986. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45987. * and the exponent defines the speed of the decay of the light with distance (reach).
  45988. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45989. */
  45990. var SpotLight = /** @class */ (function (_super) {
  45991. __extends(SpotLight, _super);
  45992. /**
  45993. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45994. * It can cast shadows.
  45995. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45996. * @param name The light friendly name
  45997. * @param position The position of the spot light in the scene
  45998. * @param direction The direction of the light in the scene
  45999. * @param angle The cone angle of the light in Radians
  46000. * @param exponent The light decay speed with the distance from the emission spot
  46001. * @param scene The scene the lights belongs to
  46002. */
  46003. function SpotLight(name, position, direction, angle, exponent, scene) {
  46004. var _this = _super.call(this, name, scene) || this;
  46005. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46006. _this._projectionTextureLightNear = 1e-6;
  46007. _this._projectionTextureLightFar = 1000.0;
  46008. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46009. _this._projectionTextureViewLightDirty = true;
  46010. _this._projectionTextureProjectionLightDirty = true;
  46011. _this._projectionTextureDirty = true;
  46012. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46013. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46014. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46015. _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);
  46016. _this.position = position;
  46017. _this.direction = direction;
  46018. _this.angle = angle;
  46019. _this.exponent = exponent;
  46020. return _this;
  46021. }
  46022. Object.defineProperty(SpotLight.prototype, "angle", {
  46023. /**
  46024. * Gets the cone angle of the spot light in Radians.
  46025. */
  46026. get: function () {
  46027. return this._angle;
  46028. },
  46029. /**
  46030. * Sets the cone angle of the spot light in Radians.
  46031. */
  46032. set: function (value) {
  46033. this._angle = value;
  46034. this._projectionTextureProjectionLightDirty = true;
  46035. this.forceProjectionMatrixCompute();
  46036. },
  46037. enumerable: true,
  46038. configurable: true
  46039. });
  46040. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46041. /**
  46042. * Allows scaling the angle of the light for shadow generation only.
  46043. */
  46044. get: function () {
  46045. return this._shadowAngleScale;
  46046. },
  46047. /**
  46048. * Allows scaling the angle of the light for shadow generation only.
  46049. */
  46050. set: function (value) {
  46051. this._shadowAngleScale = value;
  46052. this.forceProjectionMatrixCompute();
  46053. },
  46054. enumerable: true,
  46055. configurable: true
  46056. });
  46057. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46058. /**
  46059. * Allows reading the projecton texture
  46060. */
  46061. get: function () {
  46062. return this._projectionTextureMatrix;
  46063. },
  46064. enumerable: true,
  46065. configurable: true
  46066. });
  46067. ;
  46068. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46069. /**
  46070. * Gets the near clip of the Spotlight for texture projection.
  46071. */
  46072. get: function () {
  46073. return this._projectionTextureLightNear;
  46074. },
  46075. /**
  46076. * Sets the near clip of the Spotlight for texture projection.
  46077. */
  46078. set: function (value) {
  46079. this._projectionTextureLightNear = value;
  46080. this._projectionTextureProjectionLightDirty = true;
  46081. },
  46082. enumerable: true,
  46083. configurable: true
  46084. });
  46085. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46086. /**
  46087. * Gets the far clip of the Spotlight for texture projection.
  46088. */
  46089. get: function () {
  46090. return this._projectionTextureLightFar;
  46091. },
  46092. /**
  46093. * Sets the far clip of the Spotlight for texture projection.
  46094. */
  46095. set: function (value) {
  46096. this._projectionTextureLightFar = value;
  46097. this._projectionTextureProjectionLightDirty = true;
  46098. },
  46099. enumerable: true,
  46100. configurable: true
  46101. });
  46102. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46103. /**
  46104. * Gets the Up vector of the Spotlight for texture projection.
  46105. */
  46106. get: function () {
  46107. return this._projectionTextureUpDirection;
  46108. },
  46109. /**
  46110. * Sets the Up vector of the Spotlight for texture projection.
  46111. */
  46112. set: function (value) {
  46113. this._projectionTextureUpDirection = value;
  46114. this._projectionTextureProjectionLightDirty = true;
  46115. },
  46116. enumerable: true,
  46117. configurable: true
  46118. });
  46119. ;
  46120. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46121. /**
  46122. * Gets the projection texture of the light.
  46123. */
  46124. get: function () {
  46125. return this._projectionTexture;
  46126. },
  46127. /**
  46128. * Sets the projection texture of the light.
  46129. */
  46130. set: function (value) {
  46131. this._projectionTexture = value;
  46132. this._projectionTextureDirty = true;
  46133. },
  46134. enumerable: true,
  46135. configurable: true
  46136. });
  46137. /**
  46138. * Returns the string "SpotLight".
  46139. * @returns the class name
  46140. */
  46141. SpotLight.prototype.getClassName = function () {
  46142. return "SpotLight";
  46143. };
  46144. /**
  46145. * Returns the integer 2.
  46146. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46147. */
  46148. SpotLight.prototype.getTypeID = function () {
  46149. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46150. };
  46151. /**
  46152. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46153. */
  46154. SpotLight.prototype._setDirection = function (value) {
  46155. _super.prototype._setDirection.call(this, value);
  46156. this._projectionTextureViewLightDirty = true;
  46157. };
  46158. /**
  46159. * Overrides the position setter to recompute the projection texture view light Matrix.
  46160. */
  46161. SpotLight.prototype._setPosition = function (value) {
  46162. _super.prototype._setPosition.call(this, value);
  46163. this._projectionTextureViewLightDirty = true;
  46164. };
  46165. /**
  46166. * 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.
  46167. * Returns the SpotLight.
  46168. */
  46169. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46170. var activeCamera = this.getScene().activeCamera;
  46171. if (!activeCamera) {
  46172. return;
  46173. }
  46174. this._shadowAngleScale = this._shadowAngleScale || 1;
  46175. var angle = this._shadowAngleScale * this._angle;
  46176. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46177. };
  46178. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46179. this._projectionTextureViewLightDirty = false;
  46180. this._projectionTextureDirty = true;
  46181. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46182. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46183. };
  46184. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46185. this._projectionTextureProjectionLightDirty = false;
  46186. this._projectionTextureDirty = true;
  46187. var light_far = this.projectionTextureLightFar;
  46188. var light_near = this.projectionTextureLightNear;
  46189. var P = light_far / (light_far - light_near);
  46190. var Q = -P * light_near;
  46191. var S = 1.0 / Math.tan(this._angle / 2.0);
  46192. var A = 1.0;
  46193. 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);
  46194. };
  46195. /**
  46196. * Main function for light texture projection matrix computing.
  46197. */
  46198. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46199. this._projectionTextureDirty = false;
  46200. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46201. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46202. };
  46203. SpotLight.prototype._buildUniformLayout = function () {
  46204. this._uniformBuffer.addUniform("vLightData", 4);
  46205. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46206. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46207. this._uniformBuffer.addUniform("vLightDirection", 3);
  46208. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46209. this._uniformBuffer.addUniform("depthValues", 2);
  46210. this._uniformBuffer.create();
  46211. };
  46212. /**
  46213. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46214. * @param effect The effect to update
  46215. * @param lightIndex The index of the light in the effect to update
  46216. * @returns The spot light
  46217. */
  46218. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46219. var normalizeDirection;
  46220. if (this.computeTransformedInformation()) {
  46221. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46222. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46223. }
  46224. else {
  46225. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46226. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46227. }
  46228. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46229. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46230. if (this._projectionTextureViewLightDirty) {
  46231. this._computeProjectionTextureViewLightMatrix();
  46232. }
  46233. if (this._projectionTextureProjectionLightDirty) {
  46234. this._computeProjectionTextureProjectionLightMatrix();
  46235. }
  46236. if (this._projectionTextureDirty) {
  46237. this._computeProjectionTextureMatrix();
  46238. }
  46239. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46240. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46241. }
  46242. return this;
  46243. };
  46244. /**
  46245. * Disposes the light and the associated resources.
  46246. */
  46247. SpotLight.prototype.dispose = function () {
  46248. _super.prototype.dispose.call(this);
  46249. if (this._projectionTexture) {
  46250. this._projectionTexture.dispose();
  46251. }
  46252. };
  46253. __decorate([
  46254. BABYLON.serialize()
  46255. ], SpotLight.prototype, "angle", null);
  46256. __decorate([
  46257. BABYLON.serialize()
  46258. ], SpotLight.prototype, "shadowAngleScale", null);
  46259. __decorate([
  46260. BABYLON.serialize()
  46261. ], SpotLight.prototype, "exponent", void 0);
  46262. __decorate([
  46263. BABYLON.serialize()
  46264. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46265. __decorate([
  46266. BABYLON.serialize()
  46267. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46268. __decorate([
  46269. BABYLON.serialize()
  46270. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46271. __decorate([
  46272. BABYLON.serializeAsTexture("projectedLightTexture")
  46273. ], SpotLight.prototype, "_projectionTexture", void 0);
  46274. return SpotLight;
  46275. }(BABYLON.ShadowLight));
  46276. BABYLON.SpotLight = SpotLight;
  46277. })(BABYLON || (BABYLON = {}));
  46278. //# sourceMappingURL=babylon.spotLight.js.map
  46279. var BABYLON;
  46280. (function (BABYLON) {
  46281. /**
  46282. * Class used to override all child animations of a given target
  46283. */
  46284. var AnimationPropertiesOverride = /** @class */ (function () {
  46285. function AnimationPropertiesOverride() {
  46286. /**
  46287. * Gets or sets a value indicating if animation blending must be used
  46288. */
  46289. this.enableBlending = false;
  46290. /**
  46291. * Gets or sets the blending speed to use when enableBlending is true
  46292. */
  46293. this.blendingSpeed = 0.01;
  46294. /**
  46295. * Gets or sets the default loop mode to use
  46296. */
  46297. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46298. }
  46299. return AnimationPropertiesOverride;
  46300. }());
  46301. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46302. })(BABYLON || (BABYLON = {}));
  46303. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46304. var BABYLON;
  46305. (function (BABYLON) {
  46306. var AnimationRange = /** @class */ (function () {
  46307. function AnimationRange(name, from, to) {
  46308. this.name = name;
  46309. this.from = from;
  46310. this.to = to;
  46311. }
  46312. AnimationRange.prototype.clone = function () {
  46313. return new AnimationRange(this.name, this.from, this.to);
  46314. };
  46315. return AnimationRange;
  46316. }());
  46317. BABYLON.AnimationRange = AnimationRange;
  46318. /**
  46319. * Composed of a frame, and an action function
  46320. */
  46321. var AnimationEvent = /** @class */ (function () {
  46322. function AnimationEvent(frame, action, onlyOnce) {
  46323. this.frame = frame;
  46324. this.action = action;
  46325. this.onlyOnce = onlyOnce;
  46326. this.isDone = false;
  46327. }
  46328. return AnimationEvent;
  46329. }());
  46330. BABYLON.AnimationEvent = AnimationEvent;
  46331. var PathCursor = /** @class */ (function () {
  46332. function PathCursor(path) {
  46333. this.path = path;
  46334. this._onchange = new Array();
  46335. this.value = 0;
  46336. this.animations = new Array();
  46337. }
  46338. PathCursor.prototype.getPoint = function () {
  46339. var point = this.path.getPointAtLengthPosition(this.value);
  46340. return new BABYLON.Vector3(point.x, 0, point.y);
  46341. };
  46342. PathCursor.prototype.moveAhead = function (step) {
  46343. if (step === void 0) { step = 0.002; }
  46344. this.move(step);
  46345. return this;
  46346. };
  46347. PathCursor.prototype.moveBack = function (step) {
  46348. if (step === void 0) { step = 0.002; }
  46349. this.move(-step);
  46350. return this;
  46351. };
  46352. PathCursor.prototype.move = function (step) {
  46353. if (Math.abs(step) > 1) {
  46354. throw "step size should be less than 1.";
  46355. }
  46356. this.value += step;
  46357. this.ensureLimits();
  46358. this.raiseOnChange();
  46359. return this;
  46360. };
  46361. PathCursor.prototype.ensureLimits = function () {
  46362. while (this.value > 1) {
  46363. this.value -= 1;
  46364. }
  46365. while (this.value < 0) {
  46366. this.value += 1;
  46367. }
  46368. return this;
  46369. };
  46370. // used by animation engine
  46371. PathCursor.prototype.raiseOnChange = function () {
  46372. var _this = this;
  46373. this._onchange.forEach(function (f) { return f(_this); });
  46374. return this;
  46375. };
  46376. PathCursor.prototype.onchange = function (f) {
  46377. this._onchange.push(f);
  46378. return this;
  46379. };
  46380. return PathCursor;
  46381. }());
  46382. BABYLON.PathCursor = PathCursor;
  46383. var AnimationKeyInterpolation;
  46384. (function (AnimationKeyInterpolation) {
  46385. /**
  46386. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46387. */
  46388. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46389. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46390. var Animation = /** @class */ (function () {
  46391. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46392. this.name = name;
  46393. this.targetProperty = targetProperty;
  46394. this.framePerSecond = framePerSecond;
  46395. this.dataType = dataType;
  46396. this.loopMode = loopMode;
  46397. this.enableBlending = enableBlending;
  46398. this._runtimeAnimations = new Array();
  46399. // The set of event that will be linked to this animation
  46400. this._events = new Array();
  46401. this.blendingSpeed = 0.01;
  46402. this._ranges = {};
  46403. this.targetPropertyPath = targetProperty.split(".");
  46404. this.dataType = dataType;
  46405. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46406. }
  46407. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46408. var dataType = undefined;
  46409. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46410. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46411. }
  46412. else if (from instanceof BABYLON.Quaternion) {
  46413. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46414. }
  46415. else if (from instanceof BABYLON.Vector3) {
  46416. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46417. }
  46418. else if (from instanceof BABYLON.Vector2) {
  46419. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46420. }
  46421. else if (from instanceof BABYLON.Color3) {
  46422. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46423. }
  46424. else if (from instanceof BABYLON.Size) {
  46425. dataType = Animation.ANIMATIONTYPE_SIZE;
  46426. }
  46427. if (dataType == undefined) {
  46428. return null;
  46429. }
  46430. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46431. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46432. animation.setKeys(keys);
  46433. if (easingFunction !== undefined) {
  46434. animation.setEasingFunction(easingFunction);
  46435. }
  46436. return animation;
  46437. };
  46438. /**
  46439. * Sets up an animation.
  46440. * @param property the property to animate
  46441. * @param animationType the animation type to apply
  46442. * @param easingFunction the easing function used in the animation
  46443. * @returns The created animation
  46444. */
  46445. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46446. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46447. animation.setEasingFunction(easingFunction);
  46448. return animation;
  46449. };
  46450. /**
  46451. * Create and start an animation on a node
  46452. * @param {string} name defines the name of the global animation that will be run on all nodes
  46453. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46454. * @param {string} targetProperty defines property to animate
  46455. * @param {number} framePerSecond defines the number of frame per second yo use
  46456. * @param {number} totalFrame defines the number of frames in total
  46457. * @param {any} from defines the initial value
  46458. * @param {any} to defines the final value
  46459. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46460. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46461. * @param onAnimationEnd defines the callback to call when animation end
  46462. * @returns the animatable created for this animation
  46463. */
  46464. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46465. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46466. if (!animation) {
  46467. return null;
  46468. }
  46469. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46470. };
  46471. /**
  46472. * Create and start an animation on a node and its descendants
  46473. * @param {string} name defines the name of the global animation that will be run on all nodes
  46474. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46475. * @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.
  46476. * @param {string} targetProperty defines property to animate
  46477. * @param {number} framePerSecond defines the number of frame per second yo use
  46478. * @param {number} totalFrame defines the number of frames in total
  46479. * @param {any} from defines the initial value
  46480. * @param {any} to defines the final value
  46481. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46482. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46483. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46484. * @returns the list of animatables created for all nodes
  46485. * @example https://www.babylonjs-playground.com/#MH0VLI
  46486. */
  46487. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46488. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46489. if (!animation) {
  46490. return null;
  46491. }
  46492. var scene = node.getScene();
  46493. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46494. };
  46495. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46496. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46497. if (!animation) {
  46498. return null;
  46499. }
  46500. node.animations.push(animation);
  46501. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46502. };
  46503. /**
  46504. * Transition property of the Camera to the target Value.
  46505. * @param property The property to transition
  46506. * @param targetValue The target Value of the property
  46507. * @param host The object where the property to animate belongs
  46508. * @param scene Scene used to run the animation
  46509. * @param frameRate Framerate (in frame/s) to use
  46510. * @param transition The transition type we want to use
  46511. * @param duration The duration of the animation, in milliseconds
  46512. * @param onAnimationEnd Call back trigger at the end of the animation.
  46513. */
  46514. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46515. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46516. if (duration <= 0) {
  46517. host[property] = targetValue;
  46518. if (onAnimationEnd) {
  46519. onAnimationEnd();
  46520. }
  46521. return null;
  46522. }
  46523. var endFrame = frameRate * (duration / 1000);
  46524. transition.setKeys([{
  46525. frame: 0,
  46526. value: host[property].clone ? host[property].clone() : host[property]
  46527. },
  46528. {
  46529. frame: endFrame,
  46530. value: targetValue
  46531. }]);
  46532. if (!host.animations) {
  46533. host.animations = [];
  46534. }
  46535. host.animations.push(transition);
  46536. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46537. animation.onAnimationEnd = onAnimationEnd;
  46538. return animation;
  46539. };
  46540. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46541. /**
  46542. * Return the array of runtime animations currently using this animation
  46543. */
  46544. get: function () {
  46545. return this._runtimeAnimations;
  46546. },
  46547. enumerable: true,
  46548. configurable: true
  46549. });
  46550. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46551. get: function () {
  46552. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46553. var runtimeAnimation = _a[_i];
  46554. if (!runtimeAnimation.isStopped) {
  46555. return true;
  46556. }
  46557. }
  46558. return false;
  46559. },
  46560. enumerable: true,
  46561. configurable: true
  46562. });
  46563. // Methods
  46564. /**
  46565. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46566. */
  46567. Animation.prototype.toString = function (fullDetails) {
  46568. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46569. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46570. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46571. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46572. if (fullDetails) {
  46573. ret += ", Ranges: {";
  46574. var first = true;
  46575. for (var name in this._ranges) {
  46576. if (first) {
  46577. ret += ", ";
  46578. first = false;
  46579. }
  46580. ret += name;
  46581. }
  46582. ret += "}";
  46583. }
  46584. return ret;
  46585. };
  46586. /**
  46587. * Add an event to this animation.
  46588. */
  46589. Animation.prototype.addEvent = function (event) {
  46590. this._events.push(event);
  46591. };
  46592. /**
  46593. * Remove all events found at the given frame
  46594. * @param frame
  46595. */
  46596. Animation.prototype.removeEvents = function (frame) {
  46597. for (var index = 0; index < this._events.length; index++) {
  46598. if (this._events[index].frame === frame) {
  46599. this._events.splice(index, 1);
  46600. index--;
  46601. }
  46602. }
  46603. };
  46604. Animation.prototype.getEvents = function () {
  46605. return this._events;
  46606. };
  46607. Animation.prototype.createRange = function (name, from, to) {
  46608. // check name not already in use; could happen for bones after serialized
  46609. if (!this._ranges[name]) {
  46610. this._ranges[name] = new AnimationRange(name, from, to);
  46611. }
  46612. };
  46613. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46614. if (deleteFrames === void 0) { deleteFrames = true; }
  46615. var range = this._ranges[name];
  46616. if (!range) {
  46617. return;
  46618. }
  46619. if (deleteFrames) {
  46620. var from = range.from;
  46621. var to = range.to;
  46622. // this loop MUST go high to low for multiple splices to work
  46623. for (var key = this._keys.length - 1; key >= 0; key--) {
  46624. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46625. this._keys.splice(key, 1);
  46626. }
  46627. }
  46628. }
  46629. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46630. };
  46631. Animation.prototype.getRange = function (name) {
  46632. return this._ranges[name];
  46633. };
  46634. Animation.prototype.getKeys = function () {
  46635. return this._keys;
  46636. };
  46637. Animation.prototype.getHighestFrame = function () {
  46638. var ret = 0;
  46639. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46640. if (ret < this._keys[key].frame) {
  46641. ret = this._keys[key].frame;
  46642. }
  46643. }
  46644. return ret;
  46645. };
  46646. Animation.prototype.getEasingFunction = function () {
  46647. return this._easingFunction;
  46648. };
  46649. Animation.prototype.setEasingFunction = function (easingFunction) {
  46650. this._easingFunction = easingFunction;
  46651. };
  46652. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46653. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46654. };
  46655. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46656. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46657. };
  46658. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46659. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46660. };
  46661. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46662. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46663. };
  46664. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46665. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46666. };
  46667. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46668. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46669. };
  46670. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46671. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46672. };
  46673. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46674. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46675. };
  46676. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46677. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46678. };
  46679. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46680. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46681. };
  46682. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46683. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46684. };
  46685. Animation.prototype.clone = function () {
  46686. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46687. clone.enableBlending = this.enableBlending;
  46688. clone.blendingSpeed = this.blendingSpeed;
  46689. if (this._keys) {
  46690. clone.setKeys(this._keys);
  46691. }
  46692. if (this._ranges) {
  46693. clone._ranges = {};
  46694. for (var name in this._ranges) {
  46695. var range = this._ranges[name];
  46696. if (!range) {
  46697. continue;
  46698. }
  46699. clone._ranges[name] = range.clone();
  46700. }
  46701. }
  46702. return clone;
  46703. };
  46704. Animation.prototype.setKeys = function (values) {
  46705. this._keys = values.slice(0);
  46706. };
  46707. Animation.prototype.serialize = function () {
  46708. var serializationObject = {};
  46709. serializationObject.name = this.name;
  46710. serializationObject.property = this.targetProperty;
  46711. serializationObject.framePerSecond = this.framePerSecond;
  46712. serializationObject.dataType = this.dataType;
  46713. serializationObject.loopBehavior = this.loopMode;
  46714. serializationObject.enableBlending = this.enableBlending;
  46715. serializationObject.blendingSpeed = this.blendingSpeed;
  46716. var dataType = this.dataType;
  46717. serializationObject.keys = [];
  46718. var keys = this.getKeys();
  46719. for (var index = 0; index < keys.length; index++) {
  46720. var animationKey = keys[index];
  46721. var key = {};
  46722. key.frame = animationKey.frame;
  46723. switch (dataType) {
  46724. case Animation.ANIMATIONTYPE_FLOAT:
  46725. key.values = [animationKey.value];
  46726. break;
  46727. case Animation.ANIMATIONTYPE_QUATERNION:
  46728. case Animation.ANIMATIONTYPE_MATRIX:
  46729. case Animation.ANIMATIONTYPE_VECTOR3:
  46730. case Animation.ANIMATIONTYPE_COLOR3:
  46731. key.values = animationKey.value.asArray();
  46732. break;
  46733. }
  46734. serializationObject.keys.push(key);
  46735. }
  46736. serializationObject.ranges = [];
  46737. for (var name in this._ranges) {
  46738. var source = this._ranges[name];
  46739. if (!source) {
  46740. continue;
  46741. }
  46742. var range = {};
  46743. range.name = name;
  46744. range.from = source.from;
  46745. range.to = source.to;
  46746. serializationObject.ranges.push(range);
  46747. }
  46748. return serializationObject;
  46749. };
  46750. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46751. get: function () {
  46752. return Animation._ANIMATIONTYPE_FLOAT;
  46753. },
  46754. enumerable: true,
  46755. configurable: true
  46756. });
  46757. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46758. get: function () {
  46759. return Animation._ANIMATIONTYPE_VECTOR3;
  46760. },
  46761. enumerable: true,
  46762. configurable: true
  46763. });
  46764. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46765. get: function () {
  46766. return Animation._ANIMATIONTYPE_VECTOR2;
  46767. },
  46768. enumerable: true,
  46769. configurable: true
  46770. });
  46771. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46772. get: function () {
  46773. return Animation._ANIMATIONTYPE_SIZE;
  46774. },
  46775. enumerable: true,
  46776. configurable: true
  46777. });
  46778. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46779. get: function () {
  46780. return Animation._ANIMATIONTYPE_QUATERNION;
  46781. },
  46782. enumerable: true,
  46783. configurable: true
  46784. });
  46785. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46786. get: function () {
  46787. return Animation._ANIMATIONTYPE_MATRIX;
  46788. },
  46789. enumerable: true,
  46790. configurable: true
  46791. });
  46792. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46793. get: function () {
  46794. return Animation._ANIMATIONTYPE_COLOR3;
  46795. },
  46796. enumerable: true,
  46797. configurable: true
  46798. });
  46799. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46800. get: function () {
  46801. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46802. },
  46803. enumerable: true,
  46804. configurable: true
  46805. });
  46806. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46807. get: function () {
  46808. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46809. },
  46810. enumerable: true,
  46811. configurable: true
  46812. });
  46813. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46814. get: function () {
  46815. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46816. },
  46817. enumerable: true,
  46818. configurable: true
  46819. });
  46820. Animation.Parse = function (parsedAnimation) {
  46821. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46822. var dataType = parsedAnimation.dataType;
  46823. var keys = [];
  46824. var data;
  46825. var index;
  46826. if (parsedAnimation.enableBlending) {
  46827. animation.enableBlending = parsedAnimation.enableBlending;
  46828. }
  46829. if (parsedAnimation.blendingSpeed) {
  46830. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46831. }
  46832. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46833. var key = parsedAnimation.keys[index];
  46834. var inTangent;
  46835. var outTangent;
  46836. switch (dataType) {
  46837. case Animation.ANIMATIONTYPE_FLOAT:
  46838. data = key.values[0];
  46839. if (key.values.length >= 1) {
  46840. inTangent = key.values[1];
  46841. }
  46842. if (key.values.length >= 2) {
  46843. outTangent = key.values[2];
  46844. }
  46845. break;
  46846. case Animation.ANIMATIONTYPE_QUATERNION:
  46847. data = BABYLON.Quaternion.FromArray(key.values);
  46848. if (key.values.length >= 8) {
  46849. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46850. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46851. inTangent = _inTangent;
  46852. }
  46853. }
  46854. if (key.values.length >= 12) {
  46855. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46856. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46857. outTangent = _outTangent;
  46858. }
  46859. }
  46860. break;
  46861. case Animation.ANIMATIONTYPE_MATRIX:
  46862. data = BABYLON.Matrix.FromArray(key.values);
  46863. break;
  46864. case Animation.ANIMATIONTYPE_COLOR3:
  46865. data = BABYLON.Color3.FromArray(key.values);
  46866. break;
  46867. case Animation.ANIMATIONTYPE_VECTOR3:
  46868. default:
  46869. data = BABYLON.Vector3.FromArray(key.values);
  46870. break;
  46871. }
  46872. var keyData = {};
  46873. keyData.frame = key.frame;
  46874. keyData.value = data;
  46875. if (inTangent != undefined) {
  46876. keyData.inTangent = inTangent;
  46877. }
  46878. if (outTangent != undefined) {
  46879. keyData.outTangent = outTangent;
  46880. }
  46881. keys.push(keyData);
  46882. }
  46883. animation.setKeys(keys);
  46884. if (parsedAnimation.ranges) {
  46885. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46886. data = parsedAnimation.ranges[index];
  46887. animation.createRange(data.name, data.from, data.to);
  46888. }
  46889. }
  46890. return animation;
  46891. };
  46892. Animation.AppendSerializedAnimations = function (source, destination) {
  46893. if (source.animations) {
  46894. destination.animations = [];
  46895. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46896. var animation = source.animations[animationIndex];
  46897. destination.animations.push(animation.serialize());
  46898. }
  46899. }
  46900. };
  46901. Animation.AllowMatricesInterpolation = false;
  46902. // Statics
  46903. Animation._ANIMATIONTYPE_FLOAT = 0;
  46904. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46905. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46906. Animation._ANIMATIONTYPE_MATRIX = 3;
  46907. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46908. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46909. Animation._ANIMATIONTYPE_SIZE = 6;
  46910. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46911. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46912. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46913. return Animation;
  46914. }());
  46915. BABYLON.Animation = Animation;
  46916. })(BABYLON || (BABYLON = {}));
  46917. //# sourceMappingURL=babylon.animation.js.map
  46918. var BABYLON;
  46919. (function (BABYLON) {
  46920. /**
  46921. * This class defines the direct association between an animation and a target
  46922. */
  46923. var TargetedAnimation = /** @class */ (function () {
  46924. function TargetedAnimation() {
  46925. }
  46926. return TargetedAnimation;
  46927. }());
  46928. BABYLON.TargetedAnimation = TargetedAnimation;
  46929. /**
  46930. * Use this class to create coordinated animations on multiple targets
  46931. */
  46932. var AnimationGroup = /** @class */ (function () {
  46933. function AnimationGroup(name, scene) {
  46934. if (scene === void 0) { scene = null; }
  46935. this.name = name;
  46936. this._targetedAnimations = new Array();
  46937. this._animatables = new Array();
  46938. this._from = Number.MAX_VALUE;
  46939. this._to = -Number.MAX_VALUE;
  46940. this._speedRatio = 1;
  46941. this.onAnimationEndObservable = new BABYLON.Observable();
  46942. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46943. this._scene.animationGroups.push(this);
  46944. }
  46945. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46946. /**
  46947. * Define if the animations are started
  46948. */
  46949. get: function () {
  46950. return this._isStarted;
  46951. },
  46952. enumerable: true,
  46953. configurable: true
  46954. });
  46955. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46956. /**
  46957. * Gets or sets the speed ratio to use for all animations
  46958. */
  46959. get: function () {
  46960. return this._speedRatio;
  46961. },
  46962. /**
  46963. * Gets or sets the speed ratio to use for all animations
  46964. */
  46965. set: function (value) {
  46966. if (this._speedRatio === value) {
  46967. return;
  46968. }
  46969. this._speedRatio = value;
  46970. for (var index = 0; index < this._animatables.length; index++) {
  46971. var animatable = this._animatables[index];
  46972. animatable.speedRatio = this._speedRatio;
  46973. }
  46974. },
  46975. enumerable: true,
  46976. configurable: true
  46977. });
  46978. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46979. /**
  46980. * Gets the targeted animations for this animation group
  46981. */
  46982. get: function () {
  46983. return this._targetedAnimations;
  46984. },
  46985. enumerable: true,
  46986. configurable: true
  46987. });
  46988. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46989. /**
  46990. * returning the list of animatables controlled by this animation group.
  46991. */
  46992. get: function () {
  46993. return this._animatables;
  46994. },
  46995. enumerable: true,
  46996. configurable: true
  46997. });
  46998. /**
  46999. * Add an animation (with its target) in the group
  47000. * @param animation defines the animation we want to add
  47001. * @param target defines the target of the animation
  47002. * @returns the {BABYLON.TargetedAnimation} object
  47003. */
  47004. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47005. var targetedAnimation = {
  47006. animation: animation,
  47007. target: target
  47008. };
  47009. var keys = animation.getKeys();
  47010. if (this._from > keys[0].frame) {
  47011. this._from = keys[0].frame;
  47012. }
  47013. if (this._to < keys[keys.length - 1].frame) {
  47014. this._to = keys[keys.length - 1].frame;
  47015. }
  47016. this._targetedAnimations.push(targetedAnimation);
  47017. return targetedAnimation;
  47018. };
  47019. /**
  47020. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47021. * It can add constant keys at begin or end
  47022. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47023. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47024. */
  47025. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47026. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47027. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47028. beginFrame = Math.max(beginFrame, this._from);
  47029. endFrame = Math.min(endFrame, this._to);
  47030. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47031. var targetedAnimation = this._targetedAnimations[index];
  47032. var keys = targetedAnimation.animation.getKeys();
  47033. var startKey = keys[0];
  47034. var endKey = keys[keys.length - 1];
  47035. if (startKey.frame > beginFrame) {
  47036. var newKey = {
  47037. frame: beginFrame,
  47038. value: startKey.value,
  47039. inTangent: startKey.inTangent,
  47040. outTangent: startKey.outTangent,
  47041. interpolation: startKey.interpolation
  47042. };
  47043. keys.splice(0, 0, newKey);
  47044. }
  47045. if (endKey.frame < endFrame) {
  47046. var newKey = {
  47047. frame: endFrame,
  47048. value: endKey.value,
  47049. inTangent: endKey.outTangent,
  47050. outTangent: endKey.outTangent,
  47051. interpolation: endKey.interpolation
  47052. };
  47053. keys.push(newKey);
  47054. }
  47055. }
  47056. return this;
  47057. };
  47058. /**
  47059. * Start all animations on given targets
  47060. * @param loop defines if animations must loop
  47061. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47062. */
  47063. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47064. var _this = this;
  47065. if (loop === void 0) { loop = false; }
  47066. if (speedRatio === void 0) { speedRatio = 1; }
  47067. if (this._isStarted || this._targetedAnimations.length === 0) {
  47068. return this;
  47069. }
  47070. var _loop_1 = function () {
  47071. var targetedAnimation = this_1._targetedAnimations[index];
  47072. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47073. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47074. }));
  47075. };
  47076. var this_1 = this;
  47077. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47078. _loop_1();
  47079. }
  47080. this._speedRatio = speedRatio;
  47081. this._isStarted = true;
  47082. return this;
  47083. };
  47084. /**
  47085. * Pause all animations
  47086. */
  47087. AnimationGroup.prototype.pause = function () {
  47088. if (!this._isStarted) {
  47089. return this;
  47090. }
  47091. for (var index = 0; index < this._animatables.length; index++) {
  47092. var animatable = this._animatables[index];
  47093. animatable.pause();
  47094. }
  47095. return this;
  47096. };
  47097. /**
  47098. * Play all animations to initial state
  47099. * This function will start() the animations if they were not started or will restart() them if they were paused
  47100. * @param loop defines if animations must loop
  47101. */
  47102. AnimationGroup.prototype.play = function (loop) {
  47103. if (this.isStarted) {
  47104. if (loop !== undefined) {
  47105. for (var index = 0; index < this._animatables.length; index++) {
  47106. var animatable = this._animatables[index];
  47107. animatable.loopAnimation = loop;
  47108. }
  47109. }
  47110. this.restart();
  47111. }
  47112. else {
  47113. this.start(loop, this._speedRatio);
  47114. }
  47115. return this;
  47116. };
  47117. /**
  47118. * Reset all animations to initial state
  47119. */
  47120. AnimationGroup.prototype.reset = function () {
  47121. if (!this._isStarted) {
  47122. return this;
  47123. }
  47124. for (var index = 0; index < this._animatables.length; index++) {
  47125. var animatable = this._animatables[index];
  47126. animatable.reset();
  47127. }
  47128. return this;
  47129. };
  47130. /**
  47131. * Restart animations from key 0
  47132. */
  47133. AnimationGroup.prototype.restart = function () {
  47134. if (!this._isStarted) {
  47135. return this;
  47136. }
  47137. for (var index = 0; index < this._animatables.length; index++) {
  47138. var animatable = this._animatables[index];
  47139. animatable.restart();
  47140. }
  47141. return this;
  47142. };
  47143. /**
  47144. * Stop all animations
  47145. */
  47146. AnimationGroup.prototype.stop = function () {
  47147. if (!this._isStarted) {
  47148. return this;
  47149. }
  47150. for (var index = 0; index < this._animatables.length; index++) {
  47151. var animatable = this._animatables[index];
  47152. animatable.stop();
  47153. }
  47154. this._isStarted = false;
  47155. return this;
  47156. };
  47157. /**
  47158. * Goes to a specific frame in this animation group
  47159. *
  47160. * @param frame the frame number to go to
  47161. * @return the animationGroup
  47162. */
  47163. AnimationGroup.prototype.goToFrame = function (frame) {
  47164. if (!this._isStarted) {
  47165. return this;
  47166. }
  47167. for (var index = 0; index < this._animatables.length; index++) {
  47168. var animatable = this._animatables[index];
  47169. animatable.goToFrame(frame);
  47170. }
  47171. return this;
  47172. };
  47173. /**
  47174. * Dispose all associated resources
  47175. */
  47176. AnimationGroup.prototype.dispose = function () {
  47177. this._targetedAnimations = [];
  47178. this._animatables = [];
  47179. var index = this._scene.animationGroups.indexOf(this);
  47180. if (index > -1) {
  47181. this._scene.animationGroups.splice(index, 1);
  47182. }
  47183. };
  47184. return AnimationGroup;
  47185. }());
  47186. BABYLON.AnimationGroup = AnimationGroup;
  47187. })(BABYLON || (BABYLON = {}));
  47188. //# sourceMappingURL=babylon.animationGroup.js.map
  47189. var BABYLON;
  47190. (function (BABYLON) {
  47191. var RuntimeAnimation = /** @class */ (function () {
  47192. function RuntimeAnimation(target, animation) {
  47193. this._offsetsCache = {};
  47194. this._highLimitsCache = {};
  47195. this._stopped = false;
  47196. this._blendingFactor = 0;
  47197. this._ratioOffset = 0;
  47198. this._animation = animation;
  47199. this._target = target;
  47200. animation._runtimeAnimations.push(this);
  47201. }
  47202. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47203. get: function () {
  47204. return this._animation;
  47205. },
  47206. enumerable: true,
  47207. configurable: true
  47208. });
  47209. RuntimeAnimation.prototype.reset = function () {
  47210. this._offsetsCache = {};
  47211. this._highLimitsCache = {};
  47212. this.currentFrame = 0;
  47213. this._blendingFactor = 0;
  47214. this._originalBlendValue = null;
  47215. };
  47216. RuntimeAnimation.prototype.isStopped = function () {
  47217. return this._stopped;
  47218. };
  47219. RuntimeAnimation.prototype.dispose = function () {
  47220. var index = this._animation.runtimeAnimations.indexOf(this);
  47221. if (index > -1) {
  47222. this._animation.runtimeAnimations.splice(index, 1);
  47223. }
  47224. };
  47225. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47226. if (typeof value === "function") {
  47227. return value();
  47228. }
  47229. return value;
  47230. };
  47231. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47232. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47233. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47234. }
  47235. this.currentFrame = currentFrame;
  47236. var keys = this._animation.getKeys();
  47237. // Try to get a hash to find the right key
  47238. 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));
  47239. if (keys[startKeyIndex].frame >= currentFrame) {
  47240. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47241. startKeyIndex--;
  47242. }
  47243. }
  47244. for (var key = startKeyIndex; key < keys.length; key++) {
  47245. var endKey = keys[key + 1];
  47246. if (endKey.frame >= currentFrame) {
  47247. var startKey = keys[key];
  47248. var startValue = this._getKeyValue(startKey.value);
  47249. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47250. return startValue;
  47251. }
  47252. var endValue = this._getKeyValue(endKey.value);
  47253. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47254. var frameDelta = endKey.frame - startKey.frame;
  47255. // gradient : percent of currentFrame between the frame inf and the frame sup
  47256. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47257. // check for easingFunction and correction of gradient
  47258. var easingFunction = this._animation.getEasingFunction();
  47259. if (easingFunction != null) {
  47260. gradient = easingFunction.ease(gradient);
  47261. }
  47262. switch (this._animation.dataType) {
  47263. // Float
  47264. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47265. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47266. switch (loopMode) {
  47267. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47268. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47269. return floatValue;
  47270. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47271. return offsetValue * repeatCount + floatValue;
  47272. }
  47273. break;
  47274. // Quaternion
  47275. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47276. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47277. switch (loopMode) {
  47278. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47279. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47280. return quatValue;
  47281. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47282. return quatValue.add(offsetValue.scale(repeatCount));
  47283. }
  47284. return quatValue;
  47285. // Vector3
  47286. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47287. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47288. switch (loopMode) {
  47289. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47290. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47291. return vec3Value;
  47292. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47293. return vec3Value.add(offsetValue.scale(repeatCount));
  47294. }
  47295. // Vector2
  47296. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47297. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47298. switch (loopMode) {
  47299. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47300. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47301. return vec2Value;
  47302. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47303. return vec2Value.add(offsetValue.scale(repeatCount));
  47304. }
  47305. // Size
  47306. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47307. switch (loopMode) {
  47308. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47309. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47310. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47311. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47312. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47313. }
  47314. // Color3
  47315. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47316. switch (loopMode) {
  47317. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47318. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47319. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47320. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47321. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47322. }
  47323. // Matrix
  47324. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47325. switch (loopMode) {
  47326. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47327. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47328. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47329. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47330. }
  47331. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47332. return startValue;
  47333. }
  47334. default:
  47335. break;
  47336. }
  47337. break;
  47338. }
  47339. }
  47340. return this._getKeyValue(keys[keys.length - 1].value);
  47341. };
  47342. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47343. if (blend === void 0) { blend = false; }
  47344. // Set value
  47345. var path;
  47346. var destination;
  47347. var targetPropertyPath = this._animation.targetPropertyPath;
  47348. if (targetPropertyPath.length > 1) {
  47349. var property = this._target[targetPropertyPath[0]];
  47350. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47351. property = property[targetPropertyPath[index]];
  47352. }
  47353. path = targetPropertyPath[targetPropertyPath.length - 1];
  47354. destination = property;
  47355. }
  47356. else {
  47357. path = targetPropertyPath[0];
  47358. destination = this._target;
  47359. }
  47360. // Blending
  47361. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47362. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47363. if (enableBlending && this._blendingFactor <= 1.0) {
  47364. if (!this._originalBlendValue) {
  47365. if (destination[path].clone) {
  47366. this._originalBlendValue = destination[path].clone();
  47367. }
  47368. else {
  47369. this._originalBlendValue = destination[path];
  47370. }
  47371. }
  47372. if (this._originalBlendValue.prototype) {
  47373. if (this._originalBlendValue.prototype.Lerp) {
  47374. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47375. }
  47376. else {
  47377. destination[path] = currentValue;
  47378. }
  47379. }
  47380. else if (this._originalBlendValue.m) {
  47381. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47382. }
  47383. else {
  47384. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47385. }
  47386. this._blendingFactor += blendingSpeed;
  47387. }
  47388. else {
  47389. destination[path] = currentValue;
  47390. }
  47391. if (this._target.markAsDirty) {
  47392. this._target.markAsDirty(this._animation.targetProperty);
  47393. }
  47394. };
  47395. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47396. if (this._target && this._target.animationPropertiesOverride) {
  47397. return this._target.animationPropertiesOverride.loopMode;
  47398. }
  47399. return this._animation.loopMode;
  47400. };
  47401. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47402. var keys = this._animation.getKeys();
  47403. if (frame < keys[0].frame) {
  47404. frame = keys[0].frame;
  47405. }
  47406. else if (frame > keys[keys.length - 1].frame) {
  47407. frame = keys[keys.length - 1].frame;
  47408. }
  47409. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47410. this.setValue(currentValue);
  47411. };
  47412. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47413. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47414. this._ratioOffset = this._previousRatio - newRatio;
  47415. };
  47416. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47417. if (blend === void 0) { blend = false; }
  47418. var targetPropertyPath = this._animation.targetPropertyPath;
  47419. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47420. this._stopped = true;
  47421. return false;
  47422. }
  47423. var returnValue = true;
  47424. var keys = this._animation.getKeys();
  47425. // Adding a start key at frame 0 if missing
  47426. if (keys[0].frame !== 0) {
  47427. var newKey = { frame: 0, value: keys[0].value };
  47428. keys.splice(0, 0, newKey);
  47429. }
  47430. // Check limits
  47431. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47432. from = keys[0].frame;
  47433. }
  47434. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47435. to = keys[keys.length - 1].frame;
  47436. }
  47437. //to and from cannot be the same key
  47438. if (from === to) {
  47439. if (from > keys[0].frame) {
  47440. from--;
  47441. }
  47442. else if (to < keys[keys.length - 1].frame) {
  47443. to++;
  47444. }
  47445. }
  47446. // Compute ratio
  47447. var range = to - from;
  47448. var offsetValue;
  47449. // ratio represents the frame delta between from and to
  47450. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47451. var highLimitValue = 0;
  47452. this._previousDelay = delay;
  47453. this._previousRatio = ratio;
  47454. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47455. returnValue = false;
  47456. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47457. }
  47458. else {
  47459. // Get max value if required
  47460. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47461. var keyOffset = to.toString() + from.toString();
  47462. if (!this._offsetsCache[keyOffset]) {
  47463. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47464. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47465. switch (this._animation.dataType) {
  47466. // Float
  47467. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47468. this._offsetsCache[keyOffset] = toValue - fromValue;
  47469. break;
  47470. // Quaternion
  47471. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47472. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47473. break;
  47474. // Vector3
  47475. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47476. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47477. // Vector2
  47478. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47479. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47480. // Size
  47481. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47482. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47483. // Color3
  47484. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47485. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47486. default:
  47487. break;
  47488. }
  47489. this._highLimitsCache[keyOffset] = toValue;
  47490. }
  47491. highLimitValue = this._highLimitsCache[keyOffset];
  47492. offsetValue = this._offsetsCache[keyOffset];
  47493. }
  47494. }
  47495. if (offsetValue === undefined) {
  47496. switch (this._animation.dataType) {
  47497. // Float
  47498. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47499. offsetValue = 0;
  47500. break;
  47501. // Quaternion
  47502. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47503. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47504. break;
  47505. // Vector3
  47506. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47507. offsetValue = BABYLON.Vector3.Zero();
  47508. break;
  47509. // Vector2
  47510. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47511. offsetValue = BABYLON.Vector2.Zero();
  47512. break;
  47513. // Size
  47514. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47515. offsetValue = BABYLON.Size.Zero();
  47516. break;
  47517. // Color3
  47518. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47519. offsetValue = BABYLON.Color3.Black();
  47520. }
  47521. }
  47522. // Compute value
  47523. var repeatCount = (ratio / range) >> 0;
  47524. var currentFrame = returnValue ? from + ratio % range : to;
  47525. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47526. // Set value
  47527. this.setValue(currentValue);
  47528. // Check events
  47529. var events = this._animation.getEvents();
  47530. for (var index = 0; index < events.length; index++) {
  47531. // Make sure current frame has passed event frame and that event frame is within the current range
  47532. // Also, handle both forward and reverse animations
  47533. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47534. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47535. var event = events[index];
  47536. if (!event.isDone) {
  47537. // If event should be done only once, remove it.
  47538. if (event.onlyOnce) {
  47539. events.splice(index, 1);
  47540. index--;
  47541. }
  47542. event.isDone = true;
  47543. event.action();
  47544. } // Don't do anything if the event has already be done.
  47545. }
  47546. else if (events[index].isDone && !events[index].onlyOnce) {
  47547. // reset event, the animation is looping
  47548. events[index].isDone = false;
  47549. }
  47550. }
  47551. if (!returnValue) {
  47552. this._stopped = true;
  47553. }
  47554. return returnValue;
  47555. };
  47556. return RuntimeAnimation;
  47557. }());
  47558. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47559. })(BABYLON || (BABYLON = {}));
  47560. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47561. var BABYLON;
  47562. (function (BABYLON) {
  47563. var Animatable = /** @class */ (function () {
  47564. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47565. if (fromFrame === void 0) { fromFrame = 0; }
  47566. if (toFrame === void 0) { toFrame = 100; }
  47567. if (loopAnimation === void 0) { loopAnimation = false; }
  47568. if (speedRatio === void 0) { speedRatio = 1.0; }
  47569. this.target = target;
  47570. this.fromFrame = fromFrame;
  47571. this.toFrame = toFrame;
  47572. this.loopAnimation = loopAnimation;
  47573. this.onAnimationEnd = onAnimationEnd;
  47574. this._localDelayOffset = null;
  47575. this._pausedDelay = null;
  47576. this._runtimeAnimations = new Array();
  47577. this._paused = false;
  47578. this._speedRatio = 1;
  47579. this.animationStarted = false;
  47580. if (animations) {
  47581. this.appendAnimations(target, animations);
  47582. }
  47583. this._speedRatio = speedRatio;
  47584. this._scene = scene;
  47585. scene._activeAnimatables.push(this);
  47586. }
  47587. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47588. get: function () {
  47589. return this._speedRatio;
  47590. },
  47591. set: function (value) {
  47592. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47593. var animation = this._runtimeAnimations[index];
  47594. animation._prepareForSpeedRatioChange(value);
  47595. }
  47596. this._speedRatio = value;
  47597. },
  47598. enumerable: true,
  47599. configurable: true
  47600. });
  47601. // Methods
  47602. Animatable.prototype.getAnimations = function () {
  47603. return this._runtimeAnimations;
  47604. };
  47605. Animatable.prototype.appendAnimations = function (target, animations) {
  47606. for (var index = 0; index < animations.length; index++) {
  47607. var animation = animations[index];
  47608. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47609. }
  47610. };
  47611. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47612. var runtimeAnimations = this._runtimeAnimations;
  47613. for (var index = 0; index < runtimeAnimations.length; index++) {
  47614. if (runtimeAnimations[index].animation.targetProperty === property) {
  47615. return runtimeAnimations[index].animation;
  47616. }
  47617. }
  47618. return null;
  47619. };
  47620. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47621. var runtimeAnimations = this._runtimeAnimations;
  47622. for (var index = 0; index < runtimeAnimations.length; index++) {
  47623. if (runtimeAnimations[index].animation.targetProperty === property) {
  47624. return runtimeAnimations[index];
  47625. }
  47626. }
  47627. return null;
  47628. };
  47629. Animatable.prototype.reset = function () {
  47630. var runtimeAnimations = this._runtimeAnimations;
  47631. for (var index = 0; index < runtimeAnimations.length; index++) {
  47632. runtimeAnimations[index].reset();
  47633. }
  47634. // Reset to original value
  47635. for (index = 0; index < runtimeAnimations.length; index++) {
  47636. var animation = runtimeAnimations[index];
  47637. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47638. }
  47639. this._localDelayOffset = null;
  47640. this._pausedDelay = null;
  47641. };
  47642. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47643. var runtimeAnimations = this._runtimeAnimations;
  47644. for (var index = 0; index < runtimeAnimations.length; index++) {
  47645. runtimeAnimations[index].animation.enableBlending = true;
  47646. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47647. }
  47648. };
  47649. Animatable.prototype.disableBlending = function () {
  47650. var runtimeAnimations = this._runtimeAnimations;
  47651. for (var index = 0; index < runtimeAnimations.length; index++) {
  47652. runtimeAnimations[index].animation.enableBlending = false;
  47653. }
  47654. };
  47655. Animatable.prototype.goToFrame = function (frame) {
  47656. var runtimeAnimations = this._runtimeAnimations;
  47657. if (runtimeAnimations[0]) {
  47658. var fps = runtimeAnimations[0].animation.framePerSecond;
  47659. var currentFrame = runtimeAnimations[0].currentFrame;
  47660. var adjustTime = frame - currentFrame;
  47661. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47662. if (this._localDelayOffset === null) {
  47663. this._localDelayOffset = 0;
  47664. }
  47665. this._localDelayOffset -= delay;
  47666. }
  47667. for (var index = 0; index < runtimeAnimations.length; index++) {
  47668. runtimeAnimations[index].goToFrame(frame);
  47669. }
  47670. };
  47671. Animatable.prototype.pause = function () {
  47672. if (this._paused) {
  47673. return;
  47674. }
  47675. this._paused = true;
  47676. };
  47677. Animatable.prototype.restart = function () {
  47678. this._paused = false;
  47679. };
  47680. Animatable.prototype.stop = function (animationName) {
  47681. if (animationName) {
  47682. var idx = this._scene._activeAnimatables.indexOf(this);
  47683. if (idx > -1) {
  47684. var runtimeAnimations = this._runtimeAnimations;
  47685. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47686. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47687. continue;
  47688. }
  47689. runtimeAnimations[index].dispose();
  47690. runtimeAnimations.splice(index, 1);
  47691. }
  47692. if (runtimeAnimations.length == 0) {
  47693. this._scene._activeAnimatables.splice(idx, 1);
  47694. if (this.onAnimationEnd) {
  47695. this.onAnimationEnd();
  47696. }
  47697. }
  47698. }
  47699. }
  47700. else {
  47701. var index = this._scene._activeAnimatables.indexOf(this);
  47702. if (index > -1) {
  47703. this._scene._activeAnimatables.splice(index, 1);
  47704. var runtimeAnimations = this._runtimeAnimations;
  47705. for (var index = 0; index < runtimeAnimations.length; index++) {
  47706. runtimeAnimations[index].dispose();
  47707. }
  47708. if (this.onAnimationEnd) {
  47709. this.onAnimationEnd();
  47710. }
  47711. }
  47712. }
  47713. };
  47714. Animatable.prototype._animate = function (delay) {
  47715. if (this._paused) {
  47716. this.animationStarted = false;
  47717. if (this._pausedDelay === null) {
  47718. this._pausedDelay = delay;
  47719. }
  47720. return true;
  47721. }
  47722. if (this._localDelayOffset === null) {
  47723. this._localDelayOffset = delay;
  47724. this._pausedDelay = null;
  47725. }
  47726. else if (this._pausedDelay !== null) {
  47727. this._localDelayOffset += delay - this._pausedDelay;
  47728. this._pausedDelay = null;
  47729. }
  47730. // Animating
  47731. var running = false;
  47732. var runtimeAnimations = this._runtimeAnimations;
  47733. var index;
  47734. for (index = 0; index < runtimeAnimations.length; index++) {
  47735. var animation = runtimeAnimations[index];
  47736. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47737. running = running || isRunning;
  47738. }
  47739. this.animationStarted = running;
  47740. if (!running) {
  47741. // Remove from active animatables
  47742. index = this._scene._activeAnimatables.indexOf(this);
  47743. this._scene._activeAnimatables.splice(index, 1);
  47744. // Dispose all runtime animations
  47745. for (index = 0; index < runtimeAnimations.length; index++) {
  47746. runtimeAnimations[index].dispose();
  47747. }
  47748. }
  47749. if (!running && this.onAnimationEnd) {
  47750. this.onAnimationEnd();
  47751. this.onAnimationEnd = null;
  47752. }
  47753. return running;
  47754. };
  47755. return Animatable;
  47756. }());
  47757. BABYLON.Animatable = Animatable;
  47758. })(BABYLON || (BABYLON = {}));
  47759. //# sourceMappingURL=babylon.animatable.js.map
  47760. var BABYLON;
  47761. (function (BABYLON) {
  47762. var EasingFunction = /** @class */ (function () {
  47763. function EasingFunction() {
  47764. // Properties
  47765. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47766. }
  47767. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47768. get: function () {
  47769. return EasingFunction._EASINGMODE_EASEIN;
  47770. },
  47771. enumerable: true,
  47772. configurable: true
  47773. });
  47774. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47775. get: function () {
  47776. return EasingFunction._EASINGMODE_EASEOUT;
  47777. },
  47778. enumerable: true,
  47779. configurable: true
  47780. });
  47781. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47782. get: function () {
  47783. return EasingFunction._EASINGMODE_EASEINOUT;
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47789. var n = Math.min(Math.max(easingMode, 0), 2);
  47790. this._easingMode = n;
  47791. };
  47792. EasingFunction.prototype.getEasingMode = function () {
  47793. return this._easingMode;
  47794. };
  47795. EasingFunction.prototype.easeInCore = function (gradient) {
  47796. throw new Error('You must implement this method');
  47797. };
  47798. EasingFunction.prototype.ease = function (gradient) {
  47799. switch (this._easingMode) {
  47800. case EasingFunction.EASINGMODE_EASEIN:
  47801. return this.easeInCore(gradient);
  47802. case EasingFunction.EASINGMODE_EASEOUT:
  47803. return (1 - this.easeInCore(1 - gradient));
  47804. }
  47805. if (gradient >= 0.5) {
  47806. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47807. }
  47808. return (this.easeInCore(gradient * 2) * 0.5);
  47809. };
  47810. //Statics
  47811. EasingFunction._EASINGMODE_EASEIN = 0;
  47812. EasingFunction._EASINGMODE_EASEOUT = 1;
  47813. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47814. return EasingFunction;
  47815. }());
  47816. BABYLON.EasingFunction = EasingFunction;
  47817. var CircleEase = /** @class */ (function (_super) {
  47818. __extends(CircleEase, _super);
  47819. function CircleEase() {
  47820. return _super !== null && _super.apply(this, arguments) || this;
  47821. }
  47822. CircleEase.prototype.easeInCore = function (gradient) {
  47823. gradient = Math.max(0, Math.min(1, gradient));
  47824. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47825. };
  47826. return CircleEase;
  47827. }(EasingFunction));
  47828. BABYLON.CircleEase = CircleEase;
  47829. var BackEase = /** @class */ (function (_super) {
  47830. __extends(BackEase, _super);
  47831. function BackEase(amplitude) {
  47832. if (amplitude === void 0) { amplitude = 1; }
  47833. var _this = _super.call(this) || this;
  47834. _this.amplitude = amplitude;
  47835. return _this;
  47836. }
  47837. BackEase.prototype.easeInCore = function (gradient) {
  47838. var num = Math.max(0, this.amplitude);
  47839. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47840. };
  47841. return BackEase;
  47842. }(EasingFunction));
  47843. BABYLON.BackEase = BackEase;
  47844. var BounceEase = /** @class */ (function (_super) {
  47845. __extends(BounceEase, _super);
  47846. function BounceEase(bounces, bounciness) {
  47847. if (bounces === void 0) { bounces = 3; }
  47848. if (bounciness === void 0) { bounciness = 2; }
  47849. var _this = _super.call(this) || this;
  47850. _this.bounces = bounces;
  47851. _this.bounciness = bounciness;
  47852. return _this;
  47853. }
  47854. BounceEase.prototype.easeInCore = function (gradient) {
  47855. var y = Math.max(0.0, this.bounces);
  47856. var bounciness = this.bounciness;
  47857. if (bounciness <= 1.0) {
  47858. bounciness = 1.001;
  47859. }
  47860. var num9 = Math.pow(bounciness, y);
  47861. var num5 = 1.0 - bounciness;
  47862. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47863. var num15 = gradient * num4;
  47864. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47865. var num3 = Math.floor(num65);
  47866. var num13 = num3 + 1.0;
  47867. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47868. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47869. var num7 = (num8 + num12) * 0.5;
  47870. var num6 = gradient - num7;
  47871. var num2 = num7 - num8;
  47872. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47873. };
  47874. return BounceEase;
  47875. }(EasingFunction));
  47876. BABYLON.BounceEase = BounceEase;
  47877. var CubicEase = /** @class */ (function (_super) {
  47878. __extends(CubicEase, _super);
  47879. function CubicEase() {
  47880. return _super !== null && _super.apply(this, arguments) || this;
  47881. }
  47882. CubicEase.prototype.easeInCore = function (gradient) {
  47883. return (gradient * gradient * gradient);
  47884. };
  47885. return CubicEase;
  47886. }(EasingFunction));
  47887. BABYLON.CubicEase = CubicEase;
  47888. var ElasticEase = /** @class */ (function (_super) {
  47889. __extends(ElasticEase, _super);
  47890. function ElasticEase(oscillations, springiness) {
  47891. if (oscillations === void 0) { oscillations = 3; }
  47892. if (springiness === void 0) { springiness = 3; }
  47893. var _this = _super.call(this) || this;
  47894. _this.oscillations = oscillations;
  47895. _this.springiness = springiness;
  47896. return _this;
  47897. }
  47898. ElasticEase.prototype.easeInCore = function (gradient) {
  47899. var num2;
  47900. var num3 = Math.max(0.0, this.oscillations);
  47901. var num = Math.max(0.0, this.springiness);
  47902. if (num == 0) {
  47903. num2 = gradient;
  47904. }
  47905. else {
  47906. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47907. }
  47908. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47909. };
  47910. return ElasticEase;
  47911. }(EasingFunction));
  47912. BABYLON.ElasticEase = ElasticEase;
  47913. var ExponentialEase = /** @class */ (function (_super) {
  47914. __extends(ExponentialEase, _super);
  47915. function ExponentialEase(exponent) {
  47916. if (exponent === void 0) { exponent = 2; }
  47917. var _this = _super.call(this) || this;
  47918. _this.exponent = exponent;
  47919. return _this;
  47920. }
  47921. ExponentialEase.prototype.easeInCore = function (gradient) {
  47922. if (this.exponent <= 0) {
  47923. return gradient;
  47924. }
  47925. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47926. };
  47927. return ExponentialEase;
  47928. }(EasingFunction));
  47929. BABYLON.ExponentialEase = ExponentialEase;
  47930. var PowerEase = /** @class */ (function (_super) {
  47931. __extends(PowerEase, _super);
  47932. function PowerEase(power) {
  47933. if (power === void 0) { power = 2; }
  47934. var _this = _super.call(this) || this;
  47935. _this.power = power;
  47936. return _this;
  47937. }
  47938. PowerEase.prototype.easeInCore = function (gradient) {
  47939. var y = Math.max(0.0, this.power);
  47940. return Math.pow(gradient, y);
  47941. };
  47942. return PowerEase;
  47943. }(EasingFunction));
  47944. BABYLON.PowerEase = PowerEase;
  47945. var QuadraticEase = /** @class */ (function (_super) {
  47946. __extends(QuadraticEase, _super);
  47947. function QuadraticEase() {
  47948. return _super !== null && _super.apply(this, arguments) || this;
  47949. }
  47950. QuadraticEase.prototype.easeInCore = function (gradient) {
  47951. return (gradient * gradient);
  47952. };
  47953. return QuadraticEase;
  47954. }(EasingFunction));
  47955. BABYLON.QuadraticEase = QuadraticEase;
  47956. var QuarticEase = /** @class */ (function (_super) {
  47957. __extends(QuarticEase, _super);
  47958. function QuarticEase() {
  47959. return _super !== null && _super.apply(this, arguments) || this;
  47960. }
  47961. QuarticEase.prototype.easeInCore = function (gradient) {
  47962. return (gradient * gradient * gradient * gradient);
  47963. };
  47964. return QuarticEase;
  47965. }(EasingFunction));
  47966. BABYLON.QuarticEase = QuarticEase;
  47967. var QuinticEase = /** @class */ (function (_super) {
  47968. __extends(QuinticEase, _super);
  47969. function QuinticEase() {
  47970. return _super !== null && _super.apply(this, arguments) || this;
  47971. }
  47972. QuinticEase.prototype.easeInCore = function (gradient) {
  47973. return (gradient * gradient * gradient * gradient * gradient);
  47974. };
  47975. return QuinticEase;
  47976. }(EasingFunction));
  47977. BABYLON.QuinticEase = QuinticEase;
  47978. var SineEase = /** @class */ (function (_super) {
  47979. __extends(SineEase, _super);
  47980. function SineEase() {
  47981. return _super !== null && _super.apply(this, arguments) || this;
  47982. }
  47983. SineEase.prototype.easeInCore = function (gradient) {
  47984. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47985. };
  47986. return SineEase;
  47987. }(EasingFunction));
  47988. BABYLON.SineEase = SineEase;
  47989. var BezierCurveEase = /** @class */ (function (_super) {
  47990. __extends(BezierCurveEase, _super);
  47991. function BezierCurveEase(x1, y1, x2, y2) {
  47992. if (x1 === void 0) { x1 = 0; }
  47993. if (y1 === void 0) { y1 = 0; }
  47994. if (x2 === void 0) { x2 = 1; }
  47995. if (y2 === void 0) { y2 = 1; }
  47996. var _this = _super.call(this) || this;
  47997. _this.x1 = x1;
  47998. _this.y1 = y1;
  47999. _this.x2 = x2;
  48000. _this.y2 = y2;
  48001. return _this;
  48002. }
  48003. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48004. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48005. };
  48006. return BezierCurveEase;
  48007. }(EasingFunction));
  48008. BABYLON.BezierCurveEase = BezierCurveEase;
  48009. })(BABYLON || (BABYLON = {}));
  48010. //# sourceMappingURL=babylon.easing.js.map
  48011. var BABYLON;
  48012. (function (BABYLON) {
  48013. var Condition = /** @class */ (function () {
  48014. function Condition(actionManager) {
  48015. this._actionManager = actionManager;
  48016. }
  48017. Condition.prototype.isValid = function () {
  48018. return true;
  48019. };
  48020. Condition.prototype._getProperty = function (propertyPath) {
  48021. return this._actionManager._getProperty(propertyPath);
  48022. };
  48023. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48024. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48025. };
  48026. Condition.prototype.serialize = function () {
  48027. };
  48028. Condition.prototype._serialize = function (serializedCondition) {
  48029. return {
  48030. type: 2,
  48031. children: [],
  48032. name: serializedCondition.name,
  48033. properties: serializedCondition.properties
  48034. };
  48035. };
  48036. return Condition;
  48037. }());
  48038. BABYLON.Condition = Condition;
  48039. var ValueCondition = /** @class */ (function (_super) {
  48040. __extends(ValueCondition, _super);
  48041. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48042. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48043. var _this = _super.call(this, actionManager) || this;
  48044. _this.propertyPath = propertyPath;
  48045. _this.value = value;
  48046. _this.operator = operator;
  48047. _this._target = target;
  48048. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48049. _this._property = _this._getProperty(_this.propertyPath);
  48050. return _this;
  48051. }
  48052. Object.defineProperty(ValueCondition, "IsEqual", {
  48053. get: function () {
  48054. return ValueCondition._IsEqual;
  48055. },
  48056. enumerable: true,
  48057. configurable: true
  48058. });
  48059. Object.defineProperty(ValueCondition, "IsDifferent", {
  48060. get: function () {
  48061. return ValueCondition._IsDifferent;
  48062. },
  48063. enumerable: true,
  48064. configurable: true
  48065. });
  48066. Object.defineProperty(ValueCondition, "IsGreater", {
  48067. get: function () {
  48068. return ValueCondition._IsGreater;
  48069. },
  48070. enumerable: true,
  48071. configurable: true
  48072. });
  48073. Object.defineProperty(ValueCondition, "IsLesser", {
  48074. get: function () {
  48075. return ValueCondition._IsLesser;
  48076. },
  48077. enumerable: true,
  48078. configurable: true
  48079. });
  48080. // Methods
  48081. ValueCondition.prototype.isValid = function () {
  48082. switch (this.operator) {
  48083. case ValueCondition.IsGreater:
  48084. return this._effectiveTarget[this._property] > this.value;
  48085. case ValueCondition.IsLesser:
  48086. return this._effectiveTarget[this._property] < this.value;
  48087. case ValueCondition.IsEqual:
  48088. case ValueCondition.IsDifferent:
  48089. var check;
  48090. if (this.value.equals) {
  48091. check = this.value.equals(this._effectiveTarget[this._property]);
  48092. }
  48093. else {
  48094. check = this.value === this._effectiveTarget[this._property];
  48095. }
  48096. return this.operator === ValueCondition.IsEqual ? check : !check;
  48097. }
  48098. return false;
  48099. };
  48100. ValueCondition.prototype.serialize = function () {
  48101. return this._serialize({
  48102. name: "ValueCondition",
  48103. properties: [
  48104. BABYLON.Action._GetTargetProperty(this._target),
  48105. { name: "propertyPath", value: this.propertyPath },
  48106. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48107. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48108. ]
  48109. });
  48110. };
  48111. ValueCondition.GetOperatorName = function (operator) {
  48112. switch (operator) {
  48113. case ValueCondition._IsEqual: return "IsEqual";
  48114. case ValueCondition._IsDifferent: return "IsDifferent";
  48115. case ValueCondition._IsGreater: return "IsGreater";
  48116. case ValueCondition._IsLesser: return "IsLesser";
  48117. default: return "";
  48118. }
  48119. };
  48120. // Statics
  48121. ValueCondition._IsEqual = 0;
  48122. ValueCondition._IsDifferent = 1;
  48123. ValueCondition._IsGreater = 2;
  48124. ValueCondition._IsLesser = 3;
  48125. return ValueCondition;
  48126. }(Condition));
  48127. BABYLON.ValueCondition = ValueCondition;
  48128. var PredicateCondition = /** @class */ (function (_super) {
  48129. __extends(PredicateCondition, _super);
  48130. function PredicateCondition(actionManager, predicate) {
  48131. var _this = _super.call(this, actionManager) || this;
  48132. _this.predicate = predicate;
  48133. return _this;
  48134. }
  48135. PredicateCondition.prototype.isValid = function () {
  48136. return this.predicate();
  48137. };
  48138. return PredicateCondition;
  48139. }(Condition));
  48140. BABYLON.PredicateCondition = PredicateCondition;
  48141. var StateCondition = /** @class */ (function (_super) {
  48142. __extends(StateCondition, _super);
  48143. function StateCondition(actionManager, target, value) {
  48144. var _this = _super.call(this, actionManager) || this;
  48145. _this.value = value;
  48146. _this._target = target;
  48147. return _this;
  48148. }
  48149. // Methods
  48150. StateCondition.prototype.isValid = function () {
  48151. return this._target.state === this.value;
  48152. };
  48153. StateCondition.prototype.serialize = function () {
  48154. return this._serialize({
  48155. name: "StateCondition",
  48156. properties: [
  48157. BABYLON.Action._GetTargetProperty(this._target),
  48158. { name: "value", value: this.value }
  48159. ]
  48160. });
  48161. };
  48162. return StateCondition;
  48163. }(Condition));
  48164. BABYLON.StateCondition = StateCondition;
  48165. })(BABYLON || (BABYLON = {}));
  48166. //# sourceMappingURL=babylon.condition.js.map
  48167. var BABYLON;
  48168. (function (BABYLON) {
  48169. var Action = /** @class */ (function () {
  48170. function Action(triggerOptions, condition) {
  48171. this.triggerOptions = triggerOptions;
  48172. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48173. if (triggerOptions.parameter) {
  48174. this.trigger = triggerOptions.trigger;
  48175. this._triggerParameter = triggerOptions.parameter;
  48176. }
  48177. else {
  48178. this.trigger = triggerOptions;
  48179. }
  48180. this._nextActiveAction = this;
  48181. this._condition = condition;
  48182. }
  48183. // Methods
  48184. Action.prototype._prepare = function () {
  48185. };
  48186. Action.prototype.getTriggerParameter = function () {
  48187. return this._triggerParameter;
  48188. };
  48189. Action.prototype._executeCurrent = function (evt) {
  48190. if (this._nextActiveAction._condition) {
  48191. var condition = this._nextActiveAction._condition;
  48192. var currentRenderId = this._actionManager.getScene().getRenderId();
  48193. // We cache the current evaluation for the current frame
  48194. if (condition._evaluationId === currentRenderId) {
  48195. if (!condition._currentResult) {
  48196. return;
  48197. }
  48198. }
  48199. else {
  48200. condition._evaluationId = currentRenderId;
  48201. if (!condition.isValid()) {
  48202. condition._currentResult = false;
  48203. return;
  48204. }
  48205. condition._currentResult = true;
  48206. }
  48207. }
  48208. this.onBeforeExecuteObservable.notifyObservers(this);
  48209. this._nextActiveAction.execute(evt);
  48210. this.skipToNextActiveAction();
  48211. };
  48212. Action.prototype.execute = function (evt) {
  48213. };
  48214. Action.prototype.skipToNextActiveAction = function () {
  48215. if (this._nextActiveAction._child) {
  48216. if (!this._nextActiveAction._child._actionManager) {
  48217. this._nextActiveAction._child._actionManager = this._actionManager;
  48218. }
  48219. this._nextActiveAction = this._nextActiveAction._child;
  48220. }
  48221. else {
  48222. this._nextActiveAction = this;
  48223. }
  48224. };
  48225. Action.prototype.then = function (action) {
  48226. this._child = action;
  48227. action._actionManager = this._actionManager;
  48228. action._prepare();
  48229. return action;
  48230. };
  48231. Action.prototype._getProperty = function (propertyPath) {
  48232. return this._actionManager._getProperty(propertyPath);
  48233. };
  48234. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48235. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48236. };
  48237. Action.prototype.serialize = function (parent) {
  48238. };
  48239. // Called by BABYLON.Action objects in serialize(...). Internal use
  48240. Action.prototype._serialize = function (serializedAction, parent) {
  48241. var serializationObject = {
  48242. type: 1,
  48243. children: [],
  48244. name: serializedAction.name,
  48245. properties: serializedAction.properties || []
  48246. };
  48247. // Serialize child
  48248. if (this._child) {
  48249. this._child.serialize(serializationObject);
  48250. }
  48251. // Check if "this" has a condition
  48252. if (this._condition) {
  48253. var serializedCondition = this._condition.serialize();
  48254. serializedCondition.children.push(serializationObject);
  48255. if (parent) {
  48256. parent.children.push(serializedCondition);
  48257. }
  48258. return serializedCondition;
  48259. }
  48260. if (parent) {
  48261. parent.children.push(serializationObject);
  48262. }
  48263. return serializationObject;
  48264. };
  48265. Action._SerializeValueAsString = function (value) {
  48266. if (typeof value === "number") {
  48267. return value.toString();
  48268. }
  48269. if (typeof value === "boolean") {
  48270. return value ? "true" : "false";
  48271. }
  48272. if (value instanceof BABYLON.Vector2) {
  48273. return value.x + ", " + value.y;
  48274. }
  48275. if (value instanceof BABYLON.Vector3) {
  48276. return value.x + ", " + value.y + ", " + value.z;
  48277. }
  48278. if (value instanceof BABYLON.Color3) {
  48279. return value.r + ", " + value.g + ", " + value.b;
  48280. }
  48281. if (value instanceof BABYLON.Color4) {
  48282. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48283. }
  48284. return value; // string
  48285. };
  48286. Action._GetTargetProperty = function (target) {
  48287. return {
  48288. name: "target",
  48289. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48290. : target instanceof BABYLON.Light ? "LightProperties"
  48291. : target instanceof BABYLON.Camera ? "CameraProperties"
  48292. : "SceneProperties",
  48293. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48294. };
  48295. };
  48296. return Action;
  48297. }());
  48298. BABYLON.Action = Action;
  48299. })(BABYLON || (BABYLON = {}));
  48300. //# sourceMappingURL=babylon.action.js.map
  48301. var BABYLON;
  48302. (function (BABYLON) {
  48303. /**
  48304. * ActionEvent is the event beint sent when an action is triggered.
  48305. */
  48306. var ActionEvent = /** @class */ (function () {
  48307. /**
  48308. * @param source The mesh or sprite that triggered the action.
  48309. * @param pointerX The X mouse cursor position at the time of the event
  48310. * @param pointerY The Y mouse cursor position at the time of the event
  48311. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48312. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48313. */
  48314. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48315. this.source = source;
  48316. this.pointerX = pointerX;
  48317. this.pointerY = pointerY;
  48318. this.meshUnderPointer = meshUnderPointer;
  48319. this.sourceEvent = sourceEvent;
  48320. this.additionalData = additionalData;
  48321. }
  48322. /**
  48323. * Helper function to auto-create an ActionEvent from a source mesh.
  48324. * @param source The source mesh that triggered the event
  48325. * @param evt {Event} The original (browser) event
  48326. */
  48327. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48328. var scene = source.getScene();
  48329. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48330. };
  48331. /**
  48332. * Helper function to auto-create an ActionEvent from a source mesh.
  48333. * @param source The source sprite that triggered the event
  48334. * @param scene Scene associated with the sprite
  48335. * @param evt {Event} The original (browser) event
  48336. */
  48337. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48338. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48339. };
  48340. /**
  48341. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48342. * @param scene the scene where the event occurred
  48343. * @param evt {Event} The original (browser) event
  48344. */
  48345. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48346. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48347. };
  48348. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48349. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48350. };
  48351. return ActionEvent;
  48352. }());
  48353. BABYLON.ActionEvent = ActionEvent;
  48354. /**
  48355. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48356. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48357. */
  48358. var ActionManager = /** @class */ (function () {
  48359. function ActionManager(scene) {
  48360. // Members
  48361. this.actions = new Array();
  48362. this.hoverCursor = '';
  48363. this._scene = scene;
  48364. scene._actionManagers.push(this);
  48365. }
  48366. Object.defineProperty(ActionManager, "NothingTrigger", {
  48367. get: function () {
  48368. return ActionManager._NothingTrigger;
  48369. },
  48370. enumerable: true,
  48371. configurable: true
  48372. });
  48373. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48374. get: function () {
  48375. return ActionManager._OnPickTrigger;
  48376. },
  48377. enumerable: true,
  48378. configurable: true
  48379. });
  48380. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48381. get: function () {
  48382. return ActionManager._OnLeftPickTrigger;
  48383. },
  48384. enumerable: true,
  48385. configurable: true
  48386. });
  48387. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48388. get: function () {
  48389. return ActionManager._OnRightPickTrigger;
  48390. },
  48391. enumerable: true,
  48392. configurable: true
  48393. });
  48394. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48395. get: function () {
  48396. return ActionManager._OnCenterPickTrigger;
  48397. },
  48398. enumerable: true,
  48399. configurable: true
  48400. });
  48401. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48402. get: function () {
  48403. return ActionManager._OnPickDownTrigger;
  48404. },
  48405. enumerable: true,
  48406. configurable: true
  48407. });
  48408. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48409. get: function () {
  48410. return ActionManager._OnDoublePickTrigger;
  48411. },
  48412. enumerable: true,
  48413. configurable: true
  48414. });
  48415. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48416. get: function () {
  48417. return ActionManager._OnPickUpTrigger;
  48418. },
  48419. enumerable: true,
  48420. configurable: true
  48421. });
  48422. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48423. /// This trigger will only be raised if you also declared a OnPickDown
  48424. get: function () {
  48425. return ActionManager._OnPickOutTrigger;
  48426. },
  48427. enumerable: true,
  48428. configurable: true
  48429. });
  48430. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48431. get: function () {
  48432. return ActionManager._OnLongPressTrigger;
  48433. },
  48434. enumerable: true,
  48435. configurable: true
  48436. });
  48437. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48438. get: function () {
  48439. return ActionManager._OnPointerOverTrigger;
  48440. },
  48441. enumerable: true,
  48442. configurable: true
  48443. });
  48444. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48445. get: function () {
  48446. return ActionManager._OnPointerOutTrigger;
  48447. },
  48448. enumerable: true,
  48449. configurable: true
  48450. });
  48451. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48452. get: function () {
  48453. return ActionManager._OnEveryFrameTrigger;
  48454. },
  48455. enumerable: true,
  48456. configurable: true
  48457. });
  48458. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48459. get: function () {
  48460. return ActionManager._OnIntersectionEnterTrigger;
  48461. },
  48462. enumerable: true,
  48463. configurable: true
  48464. });
  48465. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48466. get: function () {
  48467. return ActionManager._OnIntersectionExitTrigger;
  48468. },
  48469. enumerable: true,
  48470. configurable: true
  48471. });
  48472. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48473. get: function () {
  48474. return ActionManager._OnKeyDownTrigger;
  48475. },
  48476. enumerable: true,
  48477. configurable: true
  48478. });
  48479. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48480. get: function () {
  48481. return ActionManager._OnKeyUpTrigger;
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. // Methods
  48487. ActionManager.prototype.dispose = function () {
  48488. var index = this._scene._actionManagers.indexOf(this);
  48489. for (var i = 0; i < this.actions.length; i++) {
  48490. var action = this.actions[i];
  48491. ActionManager.Triggers[action.trigger]--;
  48492. if (ActionManager.Triggers[action.trigger] === 0) {
  48493. delete ActionManager.Triggers[action.trigger];
  48494. }
  48495. }
  48496. if (index > -1) {
  48497. this._scene._actionManagers.splice(index, 1);
  48498. }
  48499. };
  48500. ActionManager.prototype.getScene = function () {
  48501. return this._scene;
  48502. };
  48503. /**
  48504. * Does this action manager handles actions of any of the given triggers
  48505. * @param {number[]} triggers - the triggers to be tested
  48506. * @return {boolean} whether one (or more) of the triggers is handeled
  48507. */
  48508. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48509. for (var index = 0; index < this.actions.length; index++) {
  48510. var action = this.actions[index];
  48511. if (triggers.indexOf(action.trigger) > -1) {
  48512. return true;
  48513. }
  48514. }
  48515. return false;
  48516. };
  48517. /**
  48518. * Does this action manager handles actions of a given trigger
  48519. * @param {number} trigger - the trigger to be tested
  48520. * @return {boolean} whether the trigger is handeled
  48521. */
  48522. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48523. for (var index = 0; index < this.actions.length; index++) {
  48524. var action = this.actions[index];
  48525. if (action.trigger === trigger) {
  48526. return true;
  48527. }
  48528. }
  48529. return false;
  48530. };
  48531. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48532. /**
  48533. * Does this action manager has pointer triggers
  48534. * @return {boolean} whether or not it has pointer triggers
  48535. */
  48536. get: function () {
  48537. for (var index = 0; index < this.actions.length; index++) {
  48538. var action = this.actions[index];
  48539. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48540. return true;
  48541. }
  48542. }
  48543. return false;
  48544. },
  48545. enumerable: true,
  48546. configurable: true
  48547. });
  48548. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48549. /**
  48550. * Does this action manager has pick triggers
  48551. * @return {boolean} whether or not it has pick triggers
  48552. */
  48553. get: function () {
  48554. for (var index = 0; index < this.actions.length; index++) {
  48555. var action = this.actions[index];
  48556. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48557. return true;
  48558. }
  48559. }
  48560. return false;
  48561. },
  48562. enumerable: true,
  48563. configurable: true
  48564. });
  48565. Object.defineProperty(ActionManager, "HasTriggers", {
  48566. /**
  48567. * Does exist one action manager with at least one trigger
  48568. * @return {boolean} whether or not it exists one action manager with one trigger
  48569. **/
  48570. get: function () {
  48571. for (var t in ActionManager.Triggers) {
  48572. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48573. return true;
  48574. }
  48575. }
  48576. return false;
  48577. },
  48578. enumerable: true,
  48579. configurable: true
  48580. });
  48581. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48582. /**
  48583. * Does exist one action manager with at least one pick trigger
  48584. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48585. **/
  48586. get: function () {
  48587. for (var t in ActionManager.Triggers) {
  48588. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48589. var t_int = parseInt(t);
  48590. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48591. return true;
  48592. }
  48593. }
  48594. }
  48595. return false;
  48596. },
  48597. enumerable: true,
  48598. configurable: true
  48599. });
  48600. /**
  48601. * Does exist one action manager that handles actions of a given trigger
  48602. * @param {number} trigger - the trigger to be tested
  48603. * @return {boolean} whether the trigger is handeled by at least one action manager
  48604. **/
  48605. ActionManager.HasSpecificTrigger = function (trigger) {
  48606. for (var t in ActionManager.Triggers) {
  48607. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48608. var t_int = parseInt(t);
  48609. if (t_int === trigger) {
  48610. return true;
  48611. }
  48612. }
  48613. }
  48614. return false;
  48615. };
  48616. /**
  48617. * Registers an action to this action manager
  48618. * @param {BABYLON.Action} action - the action to be registered
  48619. * @return {BABYLON.Action} the action amended (prepared) after registration
  48620. */
  48621. ActionManager.prototype.registerAction = function (action) {
  48622. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48623. if (this.getScene().actionManager !== this) {
  48624. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48625. return null;
  48626. }
  48627. }
  48628. this.actions.push(action);
  48629. if (ActionManager.Triggers[action.trigger]) {
  48630. ActionManager.Triggers[action.trigger]++;
  48631. }
  48632. else {
  48633. ActionManager.Triggers[action.trigger] = 1;
  48634. }
  48635. action._actionManager = this;
  48636. action._prepare();
  48637. return action;
  48638. };
  48639. /**
  48640. * Unregisters an action to this action manager
  48641. * @param action The action to be unregistered
  48642. * @return whether the action has been unregistered
  48643. */
  48644. ActionManager.prototype.unregisterAction = function (action) {
  48645. var index = this.actions.indexOf(action);
  48646. if (index !== -1) {
  48647. this.actions.splice(index, 1);
  48648. ActionManager.Triggers[action.trigger] -= 1;
  48649. if (ActionManager.Triggers[action.trigger] === 0) {
  48650. delete ActionManager.Triggers[action.trigger];
  48651. }
  48652. delete action._actionManager;
  48653. return true;
  48654. }
  48655. return false;
  48656. };
  48657. /**
  48658. * Process a specific trigger
  48659. * @param {number} trigger - the trigger to process
  48660. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48661. */
  48662. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48663. for (var index = 0; index < this.actions.length; index++) {
  48664. var action = this.actions[index];
  48665. if (action.trigger === trigger) {
  48666. if (evt) {
  48667. if (trigger === ActionManager.OnKeyUpTrigger
  48668. || trigger === ActionManager.OnKeyDownTrigger) {
  48669. var parameter = action.getTriggerParameter();
  48670. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48671. if (!parameter.toLowerCase) {
  48672. continue;
  48673. }
  48674. var lowerCase = parameter.toLowerCase();
  48675. if (lowerCase !== evt.sourceEvent.key) {
  48676. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48677. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48678. if (actualkey !== lowerCase) {
  48679. continue;
  48680. }
  48681. }
  48682. }
  48683. }
  48684. }
  48685. action._executeCurrent(evt);
  48686. }
  48687. }
  48688. };
  48689. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48690. var properties = propertyPath.split(".");
  48691. for (var index = 0; index < properties.length - 1; index++) {
  48692. target = target[properties[index]];
  48693. }
  48694. return target;
  48695. };
  48696. ActionManager.prototype._getProperty = function (propertyPath) {
  48697. var properties = propertyPath.split(".");
  48698. return properties[properties.length - 1];
  48699. };
  48700. ActionManager.prototype.serialize = function (name) {
  48701. var root = {
  48702. children: new Array(),
  48703. name: name,
  48704. type: 3,
  48705. properties: new Array() // Empty for root but required
  48706. };
  48707. for (var i = 0; i < this.actions.length; i++) {
  48708. var triggerObject = {
  48709. type: 0,
  48710. children: new Array(),
  48711. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48712. properties: new Array()
  48713. };
  48714. var triggerOptions = this.actions[i].triggerOptions;
  48715. if (triggerOptions && typeof triggerOptions !== "number") {
  48716. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48717. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48718. }
  48719. else {
  48720. var parameter = {};
  48721. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48722. if (triggerOptions.parameter.mesh) {
  48723. parameter._meshId = triggerOptions.parameter.mesh.id;
  48724. }
  48725. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48726. }
  48727. }
  48728. // Serialize child action, recursively
  48729. this.actions[i].serialize(triggerObject);
  48730. // Add serialized trigger
  48731. root.children.push(triggerObject);
  48732. }
  48733. return root;
  48734. };
  48735. ActionManager.Parse = function (parsedActions, object, scene) {
  48736. var actionManager = new ActionManager(scene);
  48737. if (object === null)
  48738. scene.actionManager = actionManager;
  48739. else
  48740. object.actionManager = actionManager;
  48741. // instanciate a new object
  48742. var instanciate = function (name, params) {
  48743. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48744. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48745. newInstance.constructor.apply(newInstance, params);
  48746. return newInstance;
  48747. };
  48748. var parseParameter = function (name, value, target, propertyPath) {
  48749. if (propertyPath === null) {
  48750. // String, boolean or float
  48751. var floatValue = parseFloat(value);
  48752. if (value === "true" || value === "false")
  48753. return value === "true";
  48754. else
  48755. return isNaN(floatValue) ? value : floatValue;
  48756. }
  48757. var effectiveTarget = propertyPath.split(".");
  48758. var values = value.split(",");
  48759. // Get effective Target
  48760. for (var i = 0; i < effectiveTarget.length; i++) {
  48761. target = target[effectiveTarget[i]];
  48762. }
  48763. // Return appropriate value with its type
  48764. if (typeof (target) === "boolean")
  48765. return values[0] === "true";
  48766. if (typeof (target) === "string")
  48767. return values[0];
  48768. // Parameters with multiple values such as Vector3 etc.
  48769. var split = new Array();
  48770. for (var i = 0; i < values.length; i++)
  48771. split.push(parseFloat(values[i]));
  48772. if (target instanceof BABYLON.Vector3)
  48773. return BABYLON.Vector3.FromArray(split);
  48774. if (target instanceof BABYLON.Vector4)
  48775. return BABYLON.Vector4.FromArray(split);
  48776. if (target instanceof BABYLON.Color3)
  48777. return BABYLON.Color3.FromArray(split);
  48778. if (target instanceof BABYLON.Color4)
  48779. return BABYLON.Color4.FromArray(split);
  48780. return parseFloat(values[0]);
  48781. };
  48782. // traverse graph per trigger
  48783. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48784. if (combineArray === void 0) { combineArray = null; }
  48785. if (parsedAction.detached)
  48786. return;
  48787. var parameters = new Array();
  48788. var target = null;
  48789. var propertyPath = null;
  48790. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48791. // Parameters
  48792. if (parsedAction.type === 2)
  48793. parameters.push(actionManager);
  48794. else
  48795. parameters.push(trigger);
  48796. if (combine) {
  48797. var actions = new Array();
  48798. for (var j = 0; j < parsedAction.combine.length; j++) {
  48799. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48800. }
  48801. parameters.push(actions);
  48802. }
  48803. else {
  48804. for (var i = 0; i < parsedAction.properties.length; i++) {
  48805. var value = parsedAction.properties[i].value;
  48806. var name = parsedAction.properties[i].name;
  48807. var targetType = parsedAction.properties[i].targetType;
  48808. if (name === "target")
  48809. if (targetType !== null && targetType === "SceneProperties")
  48810. value = target = scene;
  48811. else
  48812. value = target = scene.getNodeByName(value);
  48813. else if (name === "parent")
  48814. value = scene.getNodeByName(value);
  48815. else if (name === "sound")
  48816. value = scene.getSoundByName(value);
  48817. else if (name !== "propertyPath") {
  48818. if (parsedAction.type === 2 && name === "operator")
  48819. value = BABYLON.ValueCondition[value];
  48820. else
  48821. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48822. }
  48823. else {
  48824. propertyPath = value;
  48825. }
  48826. parameters.push(value);
  48827. }
  48828. }
  48829. if (combineArray === null) {
  48830. parameters.push(condition);
  48831. }
  48832. else {
  48833. parameters.push(null);
  48834. }
  48835. // If interpolate value action
  48836. if (parsedAction.name === "InterpolateValueAction") {
  48837. var param = parameters[parameters.length - 2];
  48838. parameters[parameters.length - 1] = param;
  48839. parameters[parameters.length - 2] = condition;
  48840. }
  48841. // Action or condition(s) and not CombineAction
  48842. var newAction = instanciate(parsedAction.name, parameters);
  48843. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48844. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48845. if (action)
  48846. action.then(nothing);
  48847. else
  48848. actionManager.registerAction(nothing);
  48849. action = nothing;
  48850. }
  48851. if (combineArray === null) {
  48852. if (newAction instanceof BABYLON.Condition) {
  48853. condition = newAction;
  48854. newAction = action;
  48855. }
  48856. else {
  48857. condition = null;
  48858. if (action)
  48859. action.then(newAction);
  48860. else
  48861. actionManager.registerAction(newAction);
  48862. }
  48863. }
  48864. else {
  48865. combineArray.push(newAction);
  48866. }
  48867. for (var i = 0; i < parsedAction.children.length; i++)
  48868. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48869. };
  48870. // triggers
  48871. for (var i = 0; i < parsedActions.children.length; i++) {
  48872. var triggerParams;
  48873. var trigger = parsedActions.children[i];
  48874. if (trigger.properties.length > 0) {
  48875. var param = trigger.properties[0].value;
  48876. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48877. if (value._meshId) {
  48878. value.mesh = scene.getMeshByID(value._meshId);
  48879. }
  48880. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48881. }
  48882. else
  48883. triggerParams = ActionManager[trigger.name];
  48884. for (var j = 0; j < trigger.children.length; j++) {
  48885. if (!trigger.detached)
  48886. traverse(trigger.children[j], triggerParams, null, null);
  48887. }
  48888. }
  48889. };
  48890. ActionManager.GetTriggerName = function (trigger) {
  48891. switch (trigger) {
  48892. case 0: return "NothingTrigger";
  48893. case 1: return "OnPickTrigger";
  48894. case 2: return "OnLeftPickTrigger";
  48895. case 3: return "OnRightPickTrigger";
  48896. case 4: return "OnCenterPickTrigger";
  48897. case 5: return "OnPickDownTrigger";
  48898. case 6: return "OnPickUpTrigger";
  48899. case 7: return "OnLongPressTrigger";
  48900. case 8: return "OnPointerOverTrigger";
  48901. case 9: return "OnPointerOutTrigger";
  48902. case 10: return "OnEveryFrameTrigger";
  48903. case 11: return "OnIntersectionEnterTrigger";
  48904. case 12: return "OnIntersectionExitTrigger";
  48905. case 13: return "OnKeyDownTrigger";
  48906. case 14: return "OnKeyUpTrigger";
  48907. case 15: return "OnPickOutTrigger";
  48908. default: return "";
  48909. }
  48910. };
  48911. // Statics
  48912. ActionManager._NothingTrigger = 0;
  48913. ActionManager._OnPickTrigger = 1;
  48914. ActionManager._OnLeftPickTrigger = 2;
  48915. ActionManager._OnRightPickTrigger = 3;
  48916. ActionManager._OnCenterPickTrigger = 4;
  48917. ActionManager._OnPickDownTrigger = 5;
  48918. ActionManager._OnDoublePickTrigger = 6;
  48919. ActionManager._OnPickUpTrigger = 7;
  48920. ActionManager._OnLongPressTrigger = 8;
  48921. ActionManager._OnPointerOverTrigger = 9;
  48922. ActionManager._OnPointerOutTrigger = 10;
  48923. ActionManager._OnEveryFrameTrigger = 11;
  48924. ActionManager._OnIntersectionEnterTrigger = 12;
  48925. ActionManager._OnIntersectionExitTrigger = 13;
  48926. ActionManager._OnKeyDownTrigger = 14;
  48927. ActionManager._OnKeyUpTrigger = 15;
  48928. ActionManager._OnPickOutTrigger = 16;
  48929. ActionManager.Triggers = {};
  48930. return ActionManager;
  48931. }());
  48932. BABYLON.ActionManager = ActionManager;
  48933. })(BABYLON || (BABYLON = {}));
  48934. //# sourceMappingURL=babylon.actionManager.js.map
  48935. var BABYLON;
  48936. (function (BABYLON) {
  48937. var InterpolateValueAction = /** @class */ (function (_super) {
  48938. __extends(InterpolateValueAction, _super);
  48939. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48940. if (duration === void 0) { duration = 1000; }
  48941. var _this = _super.call(this, triggerOptions, condition) || this;
  48942. _this.propertyPath = propertyPath;
  48943. _this.value = value;
  48944. _this.duration = duration;
  48945. _this.stopOtherAnimations = stopOtherAnimations;
  48946. _this.onInterpolationDone = onInterpolationDone;
  48947. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48948. _this._target = _this._effectiveTarget = target;
  48949. return _this;
  48950. }
  48951. InterpolateValueAction.prototype._prepare = function () {
  48952. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48953. this._property = this._getProperty(this.propertyPath);
  48954. };
  48955. InterpolateValueAction.prototype.execute = function () {
  48956. var _this = this;
  48957. var scene = this._actionManager.getScene();
  48958. var keys = [
  48959. {
  48960. frame: 0,
  48961. value: this._effectiveTarget[this._property]
  48962. }, {
  48963. frame: 100,
  48964. value: this.value
  48965. }
  48966. ];
  48967. var dataType;
  48968. if (typeof this.value === "number") {
  48969. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48970. }
  48971. else if (this.value instanceof BABYLON.Color3) {
  48972. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48973. }
  48974. else if (this.value instanceof BABYLON.Vector3) {
  48975. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48976. }
  48977. else if (this.value instanceof BABYLON.Matrix) {
  48978. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48979. }
  48980. else if (this.value instanceof BABYLON.Quaternion) {
  48981. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48982. }
  48983. else {
  48984. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48985. return;
  48986. }
  48987. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48988. animation.setKeys(keys);
  48989. if (this.stopOtherAnimations) {
  48990. scene.stopAnimation(this._effectiveTarget);
  48991. }
  48992. var wrapper = function () {
  48993. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48994. if (_this.onInterpolationDone) {
  48995. _this.onInterpolationDone();
  48996. }
  48997. };
  48998. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48999. };
  49000. InterpolateValueAction.prototype.serialize = function (parent) {
  49001. return _super.prototype._serialize.call(this, {
  49002. name: "InterpolateValueAction",
  49003. properties: [
  49004. BABYLON.Action._GetTargetProperty(this._target),
  49005. { name: "propertyPath", value: this.propertyPath },
  49006. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49007. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49008. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49009. ]
  49010. }, parent);
  49011. };
  49012. return InterpolateValueAction;
  49013. }(BABYLON.Action));
  49014. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49015. })(BABYLON || (BABYLON = {}));
  49016. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49017. var BABYLON;
  49018. (function (BABYLON) {
  49019. var SwitchBooleanAction = /** @class */ (function (_super) {
  49020. __extends(SwitchBooleanAction, _super);
  49021. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49022. var _this = _super.call(this, triggerOptions, condition) || this;
  49023. _this.propertyPath = propertyPath;
  49024. _this._target = _this._effectiveTarget = target;
  49025. return _this;
  49026. }
  49027. SwitchBooleanAction.prototype._prepare = function () {
  49028. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49029. this._property = this._getProperty(this.propertyPath);
  49030. };
  49031. SwitchBooleanAction.prototype.execute = function () {
  49032. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49033. };
  49034. SwitchBooleanAction.prototype.serialize = function (parent) {
  49035. return _super.prototype._serialize.call(this, {
  49036. name: "SwitchBooleanAction",
  49037. properties: [
  49038. BABYLON.Action._GetTargetProperty(this._target),
  49039. { name: "propertyPath", value: this.propertyPath }
  49040. ]
  49041. }, parent);
  49042. };
  49043. return SwitchBooleanAction;
  49044. }(BABYLON.Action));
  49045. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49046. var SetStateAction = /** @class */ (function (_super) {
  49047. __extends(SetStateAction, _super);
  49048. function SetStateAction(triggerOptions, target, value, condition) {
  49049. var _this = _super.call(this, triggerOptions, condition) || this;
  49050. _this.value = value;
  49051. _this._target = target;
  49052. return _this;
  49053. }
  49054. SetStateAction.prototype.execute = function () {
  49055. this._target.state = this.value;
  49056. };
  49057. SetStateAction.prototype.serialize = function (parent) {
  49058. return _super.prototype._serialize.call(this, {
  49059. name: "SetStateAction",
  49060. properties: [
  49061. BABYLON.Action._GetTargetProperty(this._target),
  49062. { name: "value", value: this.value }
  49063. ]
  49064. }, parent);
  49065. };
  49066. return SetStateAction;
  49067. }(BABYLON.Action));
  49068. BABYLON.SetStateAction = SetStateAction;
  49069. var SetValueAction = /** @class */ (function (_super) {
  49070. __extends(SetValueAction, _super);
  49071. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49072. var _this = _super.call(this, triggerOptions, condition) || this;
  49073. _this.propertyPath = propertyPath;
  49074. _this.value = value;
  49075. _this._target = _this._effectiveTarget = target;
  49076. return _this;
  49077. }
  49078. SetValueAction.prototype._prepare = function () {
  49079. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49080. this._property = this._getProperty(this.propertyPath);
  49081. };
  49082. SetValueAction.prototype.execute = function () {
  49083. this._effectiveTarget[this._property] = this.value;
  49084. if (this._target.markAsDirty) {
  49085. this._target.markAsDirty(this._property);
  49086. }
  49087. };
  49088. SetValueAction.prototype.serialize = function (parent) {
  49089. return _super.prototype._serialize.call(this, {
  49090. name: "SetValueAction",
  49091. properties: [
  49092. BABYLON.Action._GetTargetProperty(this._target),
  49093. { name: "propertyPath", value: this.propertyPath },
  49094. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49095. ]
  49096. }, parent);
  49097. };
  49098. return SetValueAction;
  49099. }(BABYLON.Action));
  49100. BABYLON.SetValueAction = SetValueAction;
  49101. var IncrementValueAction = /** @class */ (function (_super) {
  49102. __extends(IncrementValueAction, _super);
  49103. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49104. var _this = _super.call(this, triggerOptions, condition) || this;
  49105. _this.propertyPath = propertyPath;
  49106. _this.value = value;
  49107. _this._target = _this._effectiveTarget = target;
  49108. return _this;
  49109. }
  49110. IncrementValueAction.prototype._prepare = function () {
  49111. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49112. this._property = this._getProperty(this.propertyPath);
  49113. if (typeof this._effectiveTarget[this._property] !== "number") {
  49114. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49115. }
  49116. };
  49117. IncrementValueAction.prototype.execute = function () {
  49118. this._effectiveTarget[this._property] += this.value;
  49119. if (this._target.markAsDirty) {
  49120. this._target.markAsDirty(this._property);
  49121. }
  49122. };
  49123. IncrementValueAction.prototype.serialize = function (parent) {
  49124. return _super.prototype._serialize.call(this, {
  49125. name: "IncrementValueAction",
  49126. properties: [
  49127. BABYLON.Action._GetTargetProperty(this._target),
  49128. { name: "propertyPath", value: this.propertyPath },
  49129. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49130. ]
  49131. }, parent);
  49132. };
  49133. return IncrementValueAction;
  49134. }(BABYLON.Action));
  49135. BABYLON.IncrementValueAction = IncrementValueAction;
  49136. var PlayAnimationAction = /** @class */ (function (_super) {
  49137. __extends(PlayAnimationAction, _super);
  49138. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49139. var _this = _super.call(this, triggerOptions, condition) || this;
  49140. _this.from = from;
  49141. _this.to = to;
  49142. _this.loop = loop;
  49143. _this._target = target;
  49144. return _this;
  49145. }
  49146. PlayAnimationAction.prototype._prepare = function () {
  49147. };
  49148. PlayAnimationAction.prototype.execute = function () {
  49149. var scene = this._actionManager.getScene();
  49150. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49151. };
  49152. PlayAnimationAction.prototype.serialize = function (parent) {
  49153. return _super.prototype._serialize.call(this, {
  49154. name: "PlayAnimationAction",
  49155. properties: [
  49156. BABYLON.Action._GetTargetProperty(this._target),
  49157. { name: "from", value: String(this.from) },
  49158. { name: "to", value: String(this.to) },
  49159. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49160. ]
  49161. }, parent);
  49162. };
  49163. return PlayAnimationAction;
  49164. }(BABYLON.Action));
  49165. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49166. var StopAnimationAction = /** @class */ (function (_super) {
  49167. __extends(StopAnimationAction, _super);
  49168. function StopAnimationAction(triggerOptions, target, condition) {
  49169. var _this = _super.call(this, triggerOptions, condition) || this;
  49170. _this._target = target;
  49171. return _this;
  49172. }
  49173. StopAnimationAction.prototype._prepare = function () {
  49174. };
  49175. StopAnimationAction.prototype.execute = function () {
  49176. var scene = this._actionManager.getScene();
  49177. scene.stopAnimation(this._target);
  49178. };
  49179. StopAnimationAction.prototype.serialize = function (parent) {
  49180. return _super.prototype._serialize.call(this, {
  49181. name: "StopAnimationAction",
  49182. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49183. }, parent);
  49184. };
  49185. return StopAnimationAction;
  49186. }(BABYLON.Action));
  49187. BABYLON.StopAnimationAction = StopAnimationAction;
  49188. var DoNothingAction = /** @class */ (function (_super) {
  49189. __extends(DoNothingAction, _super);
  49190. function DoNothingAction(triggerOptions, condition) {
  49191. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49192. return _super.call(this, triggerOptions, condition) || this;
  49193. }
  49194. DoNothingAction.prototype.execute = function () {
  49195. };
  49196. DoNothingAction.prototype.serialize = function (parent) {
  49197. return _super.prototype._serialize.call(this, {
  49198. name: "DoNothingAction",
  49199. properties: []
  49200. }, parent);
  49201. };
  49202. return DoNothingAction;
  49203. }(BABYLON.Action));
  49204. BABYLON.DoNothingAction = DoNothingAction;
  49205. var CombineAction = /** @class */ (function (_super) {
  49206. __extends(CombineAction, _super);
  49207. function CombineAction(triggerOptions, children, condition) {
  49208. var _this = _super.call(this, triggerOptions, condition) || this;
  49209. _this.children = children;
  49210. return _this;
  49211. }
  49212. CombineAction.prototype._prepare = function () {
  49213. for (var index = 0; index < this.children.length; index++) {
  49214. this.children[index]._actionManager = this._actionManager;
  49215. this.children[index]._prepare();
  49216. }
  49217. };
  49218. CombineAction.prototype.execute = function (evt) {
  49219. for (var index = 0; index < this.children.length; index++) {
  49220. this.children[index].execute(evt);
  49221. }
  49222. };
  49223. CombineAction.prototype.serialize = function (parent) {
  49224. var serializationObject = _super.prototype._serialize.call(this, {
  49225. name: "CombineAction",
  49226. properties: [],
  49227. combine: []
  49228. }, parent);
  49229. for (var i = 0; i < this.children.length; i++) {
  49230. serializationObject.combine.push(this.children[i].serialize(null));
  49231. }
  49232. return serializationObject;
  49233. };
  49234. return CombineAction;
  49235. }(BABYLON.Action));
  49236. BABYLON.CombineAction = CombineAction;
  49237. var ExecuteCodeAction = /** @class */ (function (_super) {
  49238. __extends(ExecuteCodeAction, _super);
  49239. function ExecuteCodeAction(triggerOptions, func, condition) {
  49240. var _this = _super.call(this, triggerOptions, condition) || this;
  49241. _this.func = func;
  49242. return _this;
  49243. }
  49244. ExecuteCodeAction.prototype.execute = function (evt) {
  49245. this.func(evt);
  49246. };
  49247. return ExecuteCodeAction;
  49248. }(BABYLON.Action));
  49249. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49250. var SetParentAction = /** @class */ (function (_super) {
  49251. __extends(SetParentAction, _super);
  49252. function SetParentAction(triggerOptions, target, parent, condition) {
  49253. var _this = _super.call(this, triggerOptions, condition) || this;
  49254. _this._target = target;
  49255. _this._parent = parent;
  49256. return _this;
  49257. }
  49258. SetParentAction.prototype._prepare = function () {
  49259. };
  49260. SetParentAction.prototype.execute = function () {
  49261. if (this._target.parent === this._parent) {
  49262. return;
  49263. }
  49264. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49265. invertParentWorldMatrix.invert();
  49266. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49267. this._target.parent = this._parent;
  49268. };
  49269. SetParentAction.prototype.serialize = function (parent) {
  49270. return _super.prototype._serialize.call(this, {
  49271. name: "SetParentAction",
  49272. properties: [
  49273. BABYLON.Action._GetTargetProperty(this._target),
  49274. BABYLON.Action._GetTargetProperty(this._parent),
  49275. ]
  49276. }, parent);
  49277. };
  49278. return SetParentAction;
  49279. }(BABYLON.Action));
  49280. BABYLON.SetParentAction = SetParentAction;
  49281. var PlaySoundAction = /** @class */ (function (_super) {
  49282. __extends(PlaySoundAction, _super);
  49283. function PlaySoundAction(triggerOptions, sound, condition) {
  49284. var _this = _super.call(this, triggerOptions, condition) || this;
  49285. _this._sound = sound;
  49286. return _this;
  49287. }
  49288. PlaySoundAction.prototype._prepare = function () {
  49289. };
  49290. PlaySoundAction.prototype.execute = function () {
  49291. if (this._sound !== undefined)
  49292. this._sound.play();
  49293. };
  49294. PlaySoundAction.prototype.serialize = function (parent) {
  49295. return _super.prototype._serialize.call(this, {
  49296. name: "PlaySoundAction",
  49297. properties: [{ name: "sound", value: this._sound.name }]
  49298. }, parent);
  49299. };
  49300. return PlaySoundAction;
  49301. }(BABYLON.Action));
  49302. BABYLON.PlaySoundAction = PlaySoundAction;
  49303. var StopSoundAction = /** @class */ (function (_super) {
  49304. __extends(StopSoundAction, _super);
  49305. function StopSoundAction(triggerOptions, sound, condition) {
  49306. var _this = _super.call(this, triggerOptions, condition) || this;
  49307. _this._sound = sound;
  49308. return _this;
  49309. }
  49310. StopSoundAction.prototype._prepare = function () {
  49311. };
  49312. StopSoundAction.prototype.execute = function () {
  49313. if (this._sound !== undefined)
  49314. this._sound.stop();
  49315. };
  49316. StopSoundAction.prototype.serialize = function (parent) {
  49317. return _super.prototype._serialize.call(this, {
  49318. name: "StopSoundAction",
  49319. properties: [{ name: "sound", value: this._sound.name }]
  49320. }, parent);
  49321. };
  49322. return StopSoundAction;
  49323. }(BABYLON.Action));
  49324. BABYLON.StopSoundAction = StopSoundAction;
  49325. })(BABYLON || (BABYLON = {}));
  49326. //# sourceMappingURL=babylon.directActions.js.map
  49327. var BABYLON;
  49328. (function (BABYLON) {
  49329. var SpriteManager = /** @class */ (function () {
  49330. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49331. if (epsilon === void 0) { epsilon = 0.01; }
  49332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49333. this.name = name;
  49334. this.sprites = new Array();
  49335. this.renderingGroupId = 0;
  49336. this.layerMask = 0x0FFFFFFF;
  49337. this.fogEnabled = true;
  49338. this.isPickable = false;
  49339. /**
  49340. * An event triggered when the manager is disposed.
  49341. * @type {BABYLON.Observable}
  49342. */
  49343. this.onDisposeObservable = new BABYLON.Observable();
  49344. this._vertexBuffers = {};
  49345. this._capacity = capacity;
  49346. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49347. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49348. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49349. if (cellSize.width && cellSize.height) {
  49350. this.cellWidth = cellSize.width;
  49351. this.cellHeight = cellSize.height;
  49352. }
  49353. else if (cellSize !== undefined) {
  49354. this.cellWidth = cellSize;
  49355. this.cellHeight = cellSize;
  49356. }
  49357. else {
  49358. return;
  49359. }
  49360. this._epsilon = epsilon;
  49361. this._scene = scene;
  49362. this._scene.spriteManagers.push(this);
  49363. var indices = [];
  49364. var index = 0;
  49365. for (var count = 0; count < capacity; count++) {
  49366. indices.push(index);
  49367. indices.push(index + 1);
  49368. indices.push(index + 2);
  49369. indices.push(index);
  49370. indices.push(index + 2);
  49371. indices.push(index + 3);
  49372. index += 4;
  49373. }
  49374. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49375. // VBO
  49376. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49377. this._vertexData = new Float32Array(capacity * 16 * 4);
  49378. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49379. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49380. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49381. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49382. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49383. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49384. this._vertexBuffers["options"] = options;
  49385. this._vertexBuffers["cellInfo"] = cellInfo;
  49386. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49387. // Effects
  49388. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49389. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49390. }
  49391. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49392. set: function (callback) {
  49393. if (this._onDisposeObserver) {
  49394. this.onDisposeObservable.remove(this._onDisposeObserver);
  49395. }
  49396. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49397. },
  49398. enumerable: true,
  49399. configurable: true
  49400. });
  49401. Object.defineProperty(SpriteManager.prototype, "texture", {
  49402. get: function () {
  49403. return this._spriteTexture;
  49404. },
  49405. set: function (value) {
  49406. this._spriteTexture = value;
  49407. },
  49408. enumerable: true,
  49409. configurable: true
  49410. });
  49411. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49412. var arrayOffset = index * 16;
  49413. if (offsetX === 0)
  49414. offsetX = this._epsilon;
  49415. else if (offsetX === 1)
  49416. offsetX = 1 - this._epsilon;
  49417. if (offsetY === 0)
  49418. offsetY = this._epsilon;
  49419. else if (offsetY === 1)
  49420. offsetY = 1 - this._epsilon;
  49421. this._vertexData[arrayOffset] = sprite.position.x;
  49422. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49423. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49424. this._vertexData[arrayOffset + 3] = sprite.angle;
  49425. this._vertexData[arrayOffset + 4] = sprite.width;
  49426. this._vertexData[arrayOffset + 5] = sprite.height;
  49427. this._vertexData[arrayOffset + 6] = offsetX;
  49428. this._vertexData[arrayOffset + 7] = offsetY;
  49429. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49430. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49431. var offset = (sprite.cellIndex / rowSize) >> 0;
  49432. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49433. this._vertexData[arrayOffset + 11] = offset;
  49434. // Color
  49435. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49436. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49437. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49438. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49439. };
  49440. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49441. var count = Math.min(this._capacity, this.sprites.length);
  49442. var min = BABYLON.Vector3.Zero();
  49443. var max = BABYLON.Vector3.Zero();
  49444. var distance = Number.MAX_VALUE;
  49445. var currentSprite = null;
  49446. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49447. var cameraView = camera.getViewMatrix();
  49448. for (var index = 0; index < count; index++) {
  49449. var sprite = this.sprites[index];
  49450. if (!sprite) {
  49451. continue;
  49452. }
  49453. if (predicate) {
  49454. if (!predicate(sprite)) {
  49455. continue;
  49456. }
  49457. }
  49458. else if (!sprite.isPickable) {
  49459. continue;
  49460. }
  49461. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49462. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49463. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49464. if (ray.intersectsBoxMinMax(min, max)) {
  49465. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49466. if (distance > currentDistance) {
  49467. distance = currentDistance;
  49468. currentSprite = sprite;
  49469. if (fastCheck) {
  49470. break;
  49471. }
  49472. }
  49473. }
  49474. }
  49475. if (currentSprite) {
  49476. var result = new BABYLON.PickingInfo();
  49477. result.hit = true;
  49478. result.pickedSprite = currentSprite;
  49479. result.distance = distance;
  49480. return result;
  49481. }
  49482. return null;
  49483. };
  49484. SpriteManager.prototype.render = function () {
  49485. // Check
  49486. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49487. return;
  49488. var engine = this._scene.getEngine();
  49489. var baseSize = this._spriteTexture.getBaseSize();
  49490. // Sprites
  49491. var deltaTime = engine.getDeltaTime();
  49492. var max = Math.min(this._capacity, this.sprites.length);
  49493. var rowSize = baseSize.width / this.cellWidth;
  49494. var offset = 0;
  49495. for (var index = 0; index < max; index++) {
  49496. var sprite = this.sprites[index];
  49497. if (!sprite) {
  49498. continue;
  49499. }
  49500. sprite._animate(deltaTime);
  49501. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49502. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49503. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49504. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49505. }
  49506. this._buffer.update(this._vertexData);
  49507. // Render
  49508. var effect = this._effectBase;
  49509. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49510. effect = this._effectFog;
  49511. }
  49512. engine.enableEffect(effect);
  49513. var viewMatrix = this._scene.getViewMatrix();
  49514. effect.setTexture("diffuseSampler", this._spriteTexture);
  49515. effect.setMatrix("view", viewMatrix);
  49516. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49517. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49518. // Fog
  49519. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49520. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49521. effect.setColor3("vFogColor", this._scene.fogColor);
  49522. }
  49523. // VBOs
  49524. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49525. // Draw order
  49526. engine.setDepthFunctionToLessOrEqual();
  49527. effect.setBool("alphaTest", true);
  49528. engine.setColorWrite(false);
  49529. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49530. engine.setColorWrite(true);
  49531. effect.setBool("alphaTest", false);
  49532. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49533. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49534. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49535. };
  49536. SpriteManager.prototype.dispose = function () {
  49537. if (this._buffer) {
  49538. this._buffer.dispose();
  49539. this._buffer = null;
  49540. }
  49541. if (this._indexBuffer) {
  49542. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49543. this._indexBuffer = null;
  49544. }
  49545. if (this._spriteTexture) {
  49546. this._spriteTexture.dispose();
  49547. this._spriteTexture = null;
  49548. }
  49549. // Remove from scene
  49550. var index = this._scene.spriteManagers.indexOf(this);
  49551. this._scene.spriteManagers.splice(index, 1);
  49552. // Callback
  49553. this.onDisposeObservable.notifyObservers(this);
  49554. this.onDisposeObservable.clear();
  49555. };
  49556. return SpriteManager;
  49557. }());
  49558. BABYLON.SpriteManager = SpriteManager;
  49559. })(BABYLON || (BABYLON = {}));
  49560. //# sourceMappingURL=babylon.spriteManager.js.map
  49561. var BABYLON;
  49562. (function (BABYLON) {
  49563. var Sprite = /** @class */ (function () {
  49564. function Sprite(name, manager) {
  49565. this.name = name;
  49566. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49567. this.width = 1.0;
  49568. this.height = 1.0;
  49569. this.angle = 0;
  49570. this.cellIndex = 0;
  49571. this.invertU = 0;
  49572. this.invertV = 0;
  49573. this.animations = new Array();
  49574. this.isPickable = false;
  49575. this._animationStarted = false;
  49576. this._loopAnimation = false;
  49577. this._fromIndex = 0;
  49578. this._toIndex = 0;
  49579. this._delay = 0;
  49580. this._direction = 1;
  49581. this._time = 0;
  49582. this._manager = manager;
  49583. this._manager.sprites.push(this);
  49584. this.position = BABYLON.Vector3.Zero();
  49585. }
  49586. Object.defineProperty(Sprite.prototype, "size", {
  49587. get: function () {
  49588. return this.width;
  49589. },
  49590. set: function (value) {
  49591. this.width = value;
  49592. this.height = value;
  49593. },
  49594. enumerable: true,
  49595. configurable: true
  49596. });
  49597. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49598. this._fromIndex = from;
  49599. this._toIndex = to;
  49600. this._loopAnimation = loop;
  49601. this._delay = delay;
  49602. this._animationStarted = true;
  49603. this._direction = from < to ? 1 : -1;
  49604. this.cellIndex = from;
  49605. this._time = 0;
  49606. this._onAnimationEnd = onAnimationEnd;
  49607. };
  49608. Sprite.prototype.stopAnimation = function () {
  49609. this._animationStarted = false;
  49610. };
  49611. Sprite.prototype._animate = function (deltaTime) {
  49612. if (!this._animationStarted)
  49613. return;
  49614. this._time += deltaTime;
  49615. if (this._time > this._delay) {
  49616. this._time = this._time % this._delay;
  49617. this.cellIndex += this._direction;
  49618. if (this.cellIndex > this._toIndex) {
  49619. if (this._loopAnimation) {
  49620. this.cellIndex = this._fromIndex;
  49621. }
  49622. else {
  49623. this.cellIndex = this._toIndex;
  49624. this._animationStarted = false;
  49625. if (this._onAnimationEnd) {
  49626. this._onAnimationEnd();
  49627. }
  49628. if (this.disposeWhenFinishedAnimating) {
  49629. this.dispose();
  49630. }
  49631. }
  49632. }
  49633. }
  49634. };
  49635. Sprite.prototype.dispose = function () {
  49636. for (var i = 0; i < this._manager.sprites.length; i++) {
  49637. if (this._manager.sprites[i] == this) {
  49638. this._manager.sprites.splice(i, 1);
  49639. }
  49640. }
  49641. };
  49642. return Sprite;
  49643. }());
  49644. BABYLON.Sprite = Sprite;
  49645. })(BABYLON || (BABYLON = {}));
  49646. //# sourceMappingURL=babylon.sprite.js.map
  49647. var BABYLON;
  49648. (function (BABYLON) {
  49649. var IntersectionInfo = /** @class */ (function () {
  49650. function IntersectionInfo(bu, bv, distance) {
  49651. this.bu = bu;
  49652. this.bv = bv;
  49653. this.distance = distance;
  49654. this.faceId = 0;
  49655. this.subMeshId = 0;
  49656. }
  49657. return IntersectionInfo;
  49658. }());
  49659. BABYLON.IntersectionInfo = IntersectionInfo;
  49660. var PickingInfo = /** @class */ (function () {
  49661. function PickingInfo() {
  49662. this.hit = false;
  49663. this.distance = 0;
  49664. this.pickedPoint = null;
  49665. this.pickedMesh = null;
  49666. this.bu = 0;
  49667. this.bv = 0;
  49668. this.faceId = -1;
  49669. this.subMeshId = 0;
  49670. this.pickedSprite = null;
  49671. }
  49672. // Methods
  49673. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49674. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49675. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49676. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49677. return null;
  49678. }
  49679. var indices = this.pickedMesh.getIndices();
  49680. if (!indices) {
  49681. return null;
  49682. }
  49683. var result;
  49684. if (useVerticesNormals) {
  49685. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49686. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49687. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49688. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49689. normal0 = normal0.scale(this.bu);
  49690. normal1 = normal1.scale(this.bv);
  49691. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49692. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49693. }
  49694. else {
  49695. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49696. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49697. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49698. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49699. var p1p2 = vertex1.subtract(vertex2);
  49700. var p3p2 = vertex3.subtract(vertex2);
  49701. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49702. }
  49703. if (useWorldCoordinates) {
  49704. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49705. }
  49706. return BABYLON.Vector3.Normalize(result);
  49707. };
  49708. PickingInfo.prototype.getTextureCoordinates = function () {
  49709. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49710. return null;
  49711. }
  49712. var indices = this.pickedMesh.getIndices();
  49713. if (!indices) {
  49714. return null;
  49715. }
  49716. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49717. if (!uvs) {
  49718. return null;
  49719. }
  49720. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49721. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49722. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49723. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49724. uv1 = uv1.scale(this.bu);
  49725. uv2 = uv2.scale(this.bv);
  49726. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49727. };
  49728. return PickingInfo;
  49729. }());
  49730. BABYLON.PickingInfo = PickingInfo;
  49731. })(BABYLON || (BABYLON = {}));
  49732. //# sourceMappingURL=babylon.pickingInfo.js.map
  49733. var BABYLON;
  49734. (function (BABYLON) {
  49735. var Ray = /** @class */ (function () {
  49736. function Ray(origin, direction, length) {
  49737. if (length === void 0) { length = Number.MAX_VALUE; }
  49738. this.origin = origin;
  49739. this.direction = direction;
  49740. this.length = length;
  49741. }
  49742. // Methods
  49743. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49744. var d = 0.0;
  49745. var maxValue = Number.MAX_VALUE;
  49746. var inv;
  49747. var min;
  49748. var max;
  49749. var temp;
  49750. if (Math.abs(this.direction.x) < 0.0000001) {
  49751. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49752. return false;
  49753. }
  49754. }
  49755. else {
  49756. inv = 1.0 / this.direction.x;
  49757. min = (minimum.x - this.origin.x) * inv;
  49758. max = (maximum.x - this.origin.x) * inv;
  49759. if (max === -Infinity) {
  49760. max = Infinity;
  49761. }
  49762. if (min > max) {
  49763. temp = min;
  49764. min = max;
  49765. max = temp;
  49766. }
  49767. d = Math.max(min, d);
  49768. maxValue = Math.min(max, maxValue);
  49769. if (d > maxValue) {
  49770. return false;
  49771. }
  49772. }
  49773. if (Math.abs(this.direction.y) < 0.0000001) {
  49774. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49775. return false;
  49776. }
  49777. }
  49778. else {
  49779. inv = 1.0 / this.direction.y;
  49780. min = (minimum.y - this.origin.y) * inv;
  49781. max = (maximum.y - this.origin.y) * inv;
  49782. if (max === -Infinity) {
  49783. max = Infinity;
  49784. }
  49785. if (min > max) {
  49786. temp = min;
  49787. min = max;
  49788. max = temp;
  49789. }
  49790. d = Math.max(min, d);
  49791. maxValue = Math.min(max, maxValue);
  49792. if (d > maxValue) {
  49793. return false;
  49794. }
  49795. }
  49796. if (Math.abs(this.direction.z) < 0.0000001) {
  49797. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49798. return false;
  49799. }
  49800. }
  49801. else {
  49802. inv = 1.0 / this.direction.z;
  49803. min = (minimum.z - this.origin.z) * inv;
  49804. max = (maximum.z - this.origin.z) * inv;
  49805. if (max === -Infinity) {
  49806. max = Infinity;
  49807. }
  49808. if (min > max) {
  49809. temp = min;
  49810. min = max;
  49811. max = temp;
  49812. }
  49813. d = Math.max(min, d);
  49814. maxValue = Math.min(max, maxValue);
  49815. if (d > maxValue) {
  49816. return false;
  49817. }
  49818. }
  49819. return true;
  49820. };
  49821. Ray.prototype.intersectsBox = function (box) {
  49822. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49823. };
  49824. Ray.prototype.intersectsSphere = function (sphere) {
  49825. var x = sphere.center.x - this.origin.x;
  49826. var y = sphere.center.y - this.origin.y;
  49827. var z = sphere.center.z - this.origin.z;
  49828. var pyth = (x * x) + (y * y) + (z * z);
  49829. var rr = sphere.radius * sphere.radius;
  49830. if (pyth <= rr) {
  49831. return true;
  49832. }
  49833. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49834. if (dot < 0.0) {
  49835. return false;
  49836. }
  49837. var temp = pyth - (dot * dot);
  49838. return temp <= rr;
  49839. };
  49840. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49841. if (!this._edge1) {
  49842. this._edge1 = BABYLON.Vector3.Zero();
  49843. this._edge2 = BABYLON.Vector3.Zero();
  49844. this._pvec = BABYLON.Vector3.Zero();
  49845. this._tvec = BABYLON.Vector3.Zero();
  49846. this._qvec = BABYLON.Vector3.Zero();
  49847. }
  49848. vertex1.subtractToRef(vertex0, this._edge1);
  49849. vertex2.subtractToRef(vertex0, this._edge2);
  49850. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49851. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49852. if (det === 0) {
  49853. return null;
  49854. }
  49855. var invdet = 1 / det;
  49856. this.origin.subtractToRef(vertex0, this._tvec);
  49857. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49858. if (bu < 0 || bu > 1.0) {
  49859. return null;
  49860. }
  49861. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49862. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49863. if (bv < 0 || bu + bv > 1.0) {
  49864. return null;
  49865. }
  49866. //check if the distance is longer than the predefined length.
  49867. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49868. if (distance > this.length) {
  49869. return null;
  49870. }
  49871. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49872. };
  49873. Ray.prototype.intersectsPlane = function (plane) {
  49874. var distance;
  49875. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49876. if (Math.abs(result1) < 9.99999997475243E-07) {
  49877. return null;
  49878. }
  49879. else {
  49880. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49881. distance = (-plane.d - result2) / result1;
  49882. if (distance < 0.0) {
  49883. if (distance < -9.99999997475243E-07) {
  49884. return null;
  49885. }
  49886. else {
  49887. return 0;
  49888. }
  49889. }
  49890. return distance;
  49891. }
  49892. };
  49893. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49894. var tm = BABYLON.Tmp.Matrix[0];
  49895. mesh.getWorldMatrix().invertToRef(tm);
  49896. if (this._tmpRay) {
  49897. Ray.TransformToRef(this, tm, this._tmpRay);
  49898. }
  49899. else {
  49900. this._tmpRay = Ray.Transform(this, tm);
  49901. }
  49902. return mesh.intersects(this._tmpRay, fastCheck);
  49903. };
  49904. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49905. if (results) {
  49906. results.length = 0;
  49907. }
  49908. else {
  49909. results = [];
  49910. }
  49911. for (var i = 0; i < meshes.length; i++) {
  49912. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49913. if (pickInfo.hit) {
  49914. results.push(pickInfo);
  49915. }
  49916. }
  49917. results.sort(this._comparePickingInfo);
  49918. return results;
  49919. };
  49920. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49921. if (pickingInfoA.distance < pickingInfoB.distance) {
  49922. return -1;
  49923. }
  49924. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49925. return 1;
  49926. }
  49927. else {
  49928. return 0;
  49929. }
  49930. };
  49931. /**
  49932. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49933. * @param sega the first point of the segment to test the intersection against
  49934. * @param segb the second point of the segment to test the intersection against
  49935. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49936. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49937. */
  49938. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49939. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49940. var u = segb.subtract(sega);
  49941. var v = rsegb.subtract(this.origin);
  49942. var w = sega.subtract(this.origin);
  49943. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49944. var b = BABYLON.Vector3.Dot(u, v);
  49945. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49946. var d = BABYLON.Vector3.Dot(u, w);
  49947. var e = BABYLON.Vector3.Dot(v, w);
  49948. var D = a * c - b * b; // always >= 0
  49949. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49950. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49951. // compute the line parameters of the two closest points
  49952. if (D < Ray.smallnum) {
  49953. sN = 0.0; // force using point P0 on segment S1
  49954. sD = 1.0; // to prevent possible division by 0.0 later
  49955. tN = e;
  49956. tD = c;
  49957. }
  49958. else {
  49959. sN = (b * e - c * d);
  49960. tN = (a * e - b * d);
  49961. if (sN < 0.0) {
  49962. sN = 0.0;
  49963. tN = e;
  49964. tD = c;
  49965. }
  49966. else if (sN > sD) {
  49967. sN = sD;
  49968. tN = e + b;
  49969. tD = c;
  49970. }
  49971. }
  49972. if (tN < 0.0) {
  49973. tN = 0.0;
  49974. // recompute sc for this edge
  49975. if (-d < 0.0) {
  49976. sN = 0.0;
  49977. }
  49978. else if (-d > a)
  49979. sN = sD;
  49980. else {
  49981. sN = -d;
  49982. sD = a;
  49983. }
  49984. }
  49985. else if (tN > tD) {
  49986. tN = tD;
  49987. // recompute sc for this edge
  49988. if ((-d + b) < 0.0) {
  49989. sN = 0;
  49990. }
  49991. else if ((-d + b) > a) {
  49992. sN = sD;
  49993. }
  49994. else {
  49995. sN = (-d + b);
  49996. sD = a;
  49997. }
  49998. }
  49999. // finally do the division to get sc and tc
  50000. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50001. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50002. // get the difference of the two closest points
  50003. var qtc = v.multiplyByFloats(tc, tc, tc);
  50004. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50005. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50006. if (isIntersected) {
  50007. return qtc.length();
  50008. }
  50009. return -1;
  50010. };
  50011. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50012. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50013. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50014. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50015. this.direction.normalize();
  50016. return this;
  50017. };
  50018. // Statics
  50019. Ray.Zero = function () {
  50020. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50021. };
  50022. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50023. var result = Ray.Zero();
  50024. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50025. };
  50026. /**
  50027. * 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
  50028. * transformed to the given world matrix.
  50029. * @param origin The origin point
  50030. * @param end The end point
  50031. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50032. */
  50033. Ray.CreateNewFromTo = function (origin, end, world) {
  50034. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50035. var direction = end.subtract(origin);
  50036. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50037. direction.normalize();
  50038. return Ray.Transform(new Ray(origin, direction, length), world);
  50039. };
  50040. Ray.Transform = function (ray, matrix) {
  50041. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50042. Ray.TransformToRef(ray, matrix, result);
  50043. return result;
  50044. };
  50045. Ray.TransformToRef = function (ray, matrix, result) {
  50046. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50047. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50048. result.length = ray.length;
  50049. var dir = result.direction;
  50050. var len = dir.length();
  50051. if (!(len === 0 || len === 1)) {
  50052. var num = 1.0 / len;
  50053. dir.x *= num;
  50054. dir.y *= num;
  50055. dir.z *= num;
  50056. result.length *= len;
  50057. }
  50058. };
  50059. Ray.smallnum = 0.00000001;
  50060. Ray.rayl = 10e8;
  50061. return Ray;
  50062. }());
  50063. BABYLON.Ray = Ray;
  50064. })(BABYLON || (BABYLON = {}));
  50065. //# sourceMappingURL=babylon.ray.js.map
  50066. var BABYLON;
  50067. (function (BABYLON) {
  50068. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50069. if (boxMin.x > sphereCenter.x + sphereRadius)
  50070. return false;
  50071. if (sphereCenter.x - sphereRadius > boxMax.x)
  50072. return false;
  50073. if (boxMin.y > sphereCenter.y + sphereRadius)
  50074. return false;
  50075. if (sphereCenter.y - sphereRadius > boxMax.y)
  50076. return false;
  50077. if (boxMin.z > sphereCenter.z + sphereRadius)
  50078. return false;
  50079. if (sphereCenter.z - sphereRadius > boxMax.z)
  50080. return false;
  50081. return true;
  50082. };
  50083. var getLowestRoot = (function () {
  50084. var result = { root: 0, found: false };
  50085. return function (a, b, c, maxR) {
  50086. result.root = 0;
  50087. result.found = false;
  50088. var determinant = b * b - 4.0 * a * c;
  50089. if (determinant < 0)
  50090. return result;
  50091. var sqrtD = Math.sqrt(determinant);
  50092. var r1 = (-b - sqrtD) / (2.0 * a);
  50093. var r2 = (-b + sqrtD) / (2.0 * a);
  50094. if (r1 > r2) {
  50095. var temp = r2;
  50096. r2 = r1;
  50097. r1 = temp;
  50098. }
  50099. if (r1 > 0 && r1 < maxR) {
  50100. result.root = r1;
  50101. result.found = true;
  50102. return result;
  50103. }
  50104. if (r2 > 0 && r2 < maxR) {
  50105. result.root = r2;
  50106. result.found = true;
  50107. return result;
  50108. }
  50109. return result;
  50110. };
  50111. })();
  50112. var Collider = /** @class */ (function () {
  50113. function Collider() {
  50114. this._collisionPoint = BABYLON.Vector3.Zero();
  50115. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50116. this._tempVector = BABYLON.Vector3.Zero();
  50117. this._tempVector2 = BABYLON.Vector3.Zero();
  50118. this._tempVector3 = BABYLON.Vector3.Zero();
  50119. this._tempVector4 = BABYLON.Vector3.Zero();
  50120. this._edge = BABYLON.Vector3.Zero();
  50121. this._baseToVertex = BABYLON.Vector3.Zero();
  50122. this._destinationPoint = BABYLON.Vector3.Zero();
  50123. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50124. this._displacementVector = BABYLON.Vector3.Zero();
  50125. this._radius = BABYLON.Vector3.One();
  50126. this._retry = 0;
  50127. this._basePointWorld = BABYLON.Vector3.Zero();
  50128. this._velocityWorld = BABYLON.Vector3.Zero();
  50129. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50130. this._collisionMask = -1;
  50131. }
  50132. Object.defineProperty(Collider.prototype, "collisionMask", {
  50133. get: function () {
  50134. return this._collisionMask;
  50135. },
  50136. set: function (mask) {
  50137. this._collisionMask = !isNaN(mask) ? mask : -1;
  50138. },
  50139. enumerable: true,
  50140. configurable: true
  50141. });
  50142. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50143. /**
  50144. * Gets the plane normal used to compute the sliding response (in local space)
  50145. */
  50146. get: function () {
  50147. return this._slidePlaneNormal;
  50148. },
  50149. enumerable: true,
  50150. configurable: true
  50151. });
  50152. // Methods
  50153. Collider.prototype._initialize = function (source, dir, e) {
  50154. this._velocity = dir;
  50155. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50156. this._basePoint = source;
  50157. source.multiplyToRef(this._radius, this._basePointWorld);
  50158. dir.multiplyToRef(this._radius, this._velocityWorld);
  50159. this._velocityWorldLength = this._velocityWorld.length();
  50160. this._epsilon = e;
  50161. this.collisionFound = false;
  50162. };
  50163. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50164. pa.subtractToRef(point, this._tempVector);
  50165. pb.subtractToRef(point, this._tempVector2);
  50166. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50167. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50168. if (d < 0)
  50169. return false;
  50170. pc.subtractToRef(point, this._tempVector3);
  50171. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50172. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50173. if (d < 0)
  50174. return false;
  50175. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50176. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50177. return d >= 0;
  50178. };
  50179. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50180. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50181. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50182. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50183. return false;
  50184. }
  50185. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50186. return false;
  50187. return true;
  50188. };
  50189. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50190. var t0;
  50191. var embeddedInPlane = false;
  50192. //defensive programming, actually not needed.
  50193. if (!trianglePlaneArray) {
  50194. trianglePlaneArray = [];
  50195. }
  50196. if (!trianglePlaneArray[faceIndex]) {
  50197. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50198. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50199. }
  50200. var trianglePlane = trianglePlaneArray[faceIndex];
  50201. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50202. return;
  50203. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50204. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50205. if (normalDotVelocity == 0) {
  50206. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50207. return;
  50208. embeddedInPlane = true;
  50209. t0 = 0;
  50210. }
  50211. else {
  50212. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50213. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50214. if (t0 > t1) {
  50215. var temp = t1;
  50216. t1 = t0;
  50217. t0 = temp;
  50218. }
  50219. if (t0 > 1.0 || t1 < 0.0)
  50220. return;
  50221. if (t0 < 0)
  50222. t0 = 0;
  50223. if (t0 > 1.0)
  50224. t0 = 1.0;
  50225. }
  50226. this._collisionPoint.copyFromFloats(0, 0, 0);
  50227. var found = false;
  50228. var t = 1.0;
  50229. if (!embeddedInPlane) {
  50230. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50231. this._velocity.scaleToRef(t0, this._tempVector);
  50232. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50233. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50234. found = true;
  50235. t = t0;
  50236. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50237. }
  50238. }
  50239. if (!found) {
  50240. var velocitySquaredLength = this._velocity.lengthSquared();
  50241. var a = velocitySquaredLength;
  50242. this._basePoint.subtractToRef(p1, this._tempVector);
  50243. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50244. var c = this._tempVector.lengthSquared() - 1.0;
  50245. var lowestRoot = getLowestRoot(a, b, c, t);
  50246. if (lowestRoot.found) {
  50247. t = lowestRoot.root;
  50248. found = true;
  50249. this._collisionPoint.copyFrom(p1);
  50250. }
  50251. this._basePoint.subtractToRef(p2, this._tempVector);
  50252. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50253. c = this._tempVector.lengthSquared() - 1.0;
  50254. lowestRoot = getLowestRoot(a, b, c, t);
  50255. if (lowestRoot.found) {
  50256. t = lowestRoot.root;
  50257. found = true;
  50258. this._collisionPoint.copyFrom(p2);
  50259. }
  50260. this._basePoint.subtractToRef(p3, this._tempVector);
  50261. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50262. c = this._tempVector.lengthSquared() - 1.0;
  50263. lowestRoot = getLowestRoot(a, b, c, t);
  50264. if (lowestRoot.found) {
  50265. t = lowestRoot.root;
  50266. found = true;
  50267. this._collisionPoint.copyFrom(p3);
  50268. }
  50269. p2.subtractToRef(p1, this._edge);
  50270. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50271. var edgeSquaredLength = this._edge.lengthSquared();
  50272. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50273. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50274. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50275. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50276. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50277. lowestRoot = getLowestRoot(a, b, c, t);
  50278. if (lowestRoot.found) {
  50279. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50280. if (f >= 0.0 && f <= 1.0) {
  50281. t = lowestRoot.root;
  50282. found = true;
  50283. this._edge.scaleInPlace(f);
  50284. p1.addToRef(this._edge, this._collisionPoint);
  50285. }
  50286. }
  50287. p3.subtractToRef(p2, this._edge);
  50288. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50289. edgeSquaredLength = this._edge.lengthSquared();
  50290. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50291. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50292. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50293. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50294. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50295. lowestRoot = getLowestRoot(a, b, c, t);
  50296. if (lowestRoot.found) {
  50297. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50298. if (f >= 0.0 && f <= 1.0) {
  50299. t = lowestRoot.root;
  50300. found = true;
  50301. this._edge.scaleInPlace(f);
  50302. p2.addToRef(this._edge, this._collisionPoint);
  50303. }
  50304. }
  50305. p1.subtractToRef(p3, this._edge);
  50306. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50307. edgeSquaredLength = this._edge.lengthSquared();
  50308. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50309. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50310. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50311. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50312. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50313. lowestRoot = getLowestRoot(a, b, c, t);
  50314. if (lowestRoot.found) {
  50315. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50316. if (f >= 0.0 && f <= 1.0) {
  50317. t = lowestRoot.root;
  50318. found = true;
  50319. this._edge.scaleInPlace(f);
  50320. p3.addToRef(this._edge, this._collisionPoint);
  50321. }
  50322. }
  50323. }
  50324. if (found) {
  50325. var distToCollision = t * this._velocity.length();
  50326. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50327. if (!this.intersectionPoint) {
  50328. this.intersectionPoint = this._collisionPoint.clone();
  50329. }
  50330. else {
  50331. this.intersectionPoint.copyFrom(this._collisionPoint);
  50332. }
  50333. this._nearestDistance = distToCollision;
  50334. this.collisionFound = true;
  50335. }
  50336. }
  50337. };
  50338. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50339. for (var i = indexStart; i < indexEnd; i += 3) {
  50340. var p1 = pts[indices[i] - decal];
  50341. var p2 = pts[indices[i + 1] - decal];
  50342. var p3 = pts[indices[i + 2] - decal];
  50343. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50344. }
  50345. };
  50346. Collider.prototype._getResponse = function (pos, vel) {
  50347. pos.addToRef(vel, this._destinationPoint);
  50348. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50349. this._basePoint.addToRef(vel, pos);
  50350. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50351. this._slidePlaneNormal.normalize();
  50352. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50353. pos.addInPlace(this._displacementVector);
  50354. this.intersectionPoint.addInPlace(this._displacementVector);
  50355. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50356. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50357. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50358. };
  50359. return Collider;
  50360. }());
  50361. BABYLON.Collider = Collider;
  50362. })(BABYLON || (BABYLON = {}));
  50363. //# sourceMappingURL=babylon.collider.js.map
  50364. var BABYLON;
  50365. (function (BABYLON) {
  50366. //WebWorker code will be inserted to this variable.
  50367. BABYLON.CollisionWorker = "";
  50368. var WorkerTaskType;
  50369. (function (WorkerTaskType) {
  50370. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50371. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50372. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50373. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50374. var WorkerReplyType;
  50375. (function (WorkerReplyType) {
  50376. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50377. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50378. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50379. var CollisionCoordinatorWorker = /** @class */ (function () {
  50380. function CollisionCoordinatorWorker() {
  50381. var _this = this;
  50382. this._scaledPosition = BABYLON.Vector3.Zero();
  50383. this._scaledVelocity = BABYLON.Vector3.Zero();
  50384. this.onMeshUpdated = function (transformNode) {
  50385. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50386. };
  50387. this.onGeometryUpdated = function (geometry) {
  50388. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50389. };
  50390. this._afterRender = function () {
  50391. if (!_this._init)
  50392. return;
  50393. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50394. return;
  50395. }
  50396. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50397. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50398. if (_this._runningUpdated > 4) {
  50399. return;
  50400. }
  50401. ++_this._runningUpdated;
  50402. var payload = {
  50403. updatedMeshes: _this._addUpdateMeshesList,
  50404. updatedGeometries: _this._addUpdateGeometriesList,
  50405. removedGeometries: _this._toRemoveGeometryArray,
  50406. removedMeshes: _this._toRemoveMeshesArray
  50407. };
  50408. var message = {
  50409. payload: payload,
  50410. taskType: WorkerTaskType.UPDATE
  50411. };
  50412. var serializable = [];
  50413. for (var id in payload.updatedGeometries) {
  50414. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50415. //prepare transferables
  50416. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50417. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50418. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50419. }
  50420. }
  50421. _this._worker.postMessage(message, serializable);
  50422. _this._addUpdateMeshesList = {};
  50423. _this._addUpdateGeometriesList = {};
  50424. _this._toRemoveGeometryArray = [];
  50425. _this._toRemoveMeshesArray = [];
  50426. };
  50427. this._onMessageFromWorker = function (e) {
  50428. var returnData = e.data;
  50429. if (returnData.error != WorkerReplyType.SUCCESS) {
  50430. //TODO what errors can be returned from the worker?
  50431. BABYLON.Tools.Warn("error returned from worker!");
  50432. return;
  50433. }
  50434. switch (returnData.taskType) {
  50435. case WorkerTaskType.INIT:
  50436. _this._init = true;
  50437. //Update the worked with ALL of the scene's current state
  50438. _this._scene.meshes.forEach(function (mesh) {
  50439. _this.onMeshAdded(mesh);
  50440. });
  50441. _this._scene.getGeometries().forEach(function (geometry) {
  50442. _this.onGeometryAdded(geometry);
  50443. });
  50444. break;
  50445. case WorkerTaskType.UPDATE:
  50446. _this._runningUpdated--;
  50447. break;
  50448. case WorkerTaskType.COLLIDE:
  50449. var returnPayload = returnData.payload;
  50450. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50451. return;
  50452. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50453. if (callback) {
  50454. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50455. if (mesh) {
  50456. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50457. }
  50458. }
  50459. //cleanup
  50460. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50461. break;
  50462. }
  50463. };
  50464. this._collisionsCallbackArray = [];
  50465. this._init = false;
  50466. this._runningUpdated = 0;
  50467. this._addUpdateMeshesList = {};
  50468. this._addUpdateGeometriesList = {};
  50469. this._toRemoveGeometryArray = [];
  50470. this._toRemoveMeshesArray = [];
  50471. }
  50472. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50473. if (!this._init)
  50474. return;
  50475. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50476. return;
  50477. position.divideToRef(collider._radius, this._scaledPosition);
  50478. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50479. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50480. var payload = {
  50481. collider: {
  50482. position: this._scaledPosition.asArray(),
  50483. velocity: this._scaledVelocity.asArray(),
  50484. radius: collider._radius.asArray()
  50485. },
  50486. collisionId: collisionIndex,
  50487. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50488. maximumRetry: maximumRetry
  50489. };
  50490. var message = {
  50491. payload: payload,
  50492. taskType: WorkerTaskType.COLLIDE
  50493. };
  50494. this._worker.postMessage(message);
  50495. };
  50496. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50497. this._scene = scene;
  50498. this._scene.registerAfterRender(this._afterRender);
  50499. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50500. this._worker = new Worker(workerUrl);
  50501. this._worker.onmessage = this._onMessageFromWorker;
  50502. var message = {
  50503. payload: {},
  50504. taskType: WorkerTaskType.INIT
  50505. };
  50506. this._worker.postMessage(message);
  50507. };
  50508. CollisionCoordinatorWorker.prototype.destroy = function () {
  50509. this._scene.unregisterAfterRender(this._afterRender);
  50510. this._worker.terminate();
  50511. };
  50512. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50513. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50514. this.onMeshUpdated(mesh);
  50515. };
  50516. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50517. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50518. };
  50519. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50520. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50521. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50522. this.onGeometryUpdated(geometry);
  50523. };
  50524. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50525. this._toRemoveGeometryArray.push(geometry.id);
  50526. };
  50527. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50528. var submeshes = [];
  50529. if (mesh.subMeshes) {
  50530. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50531. var boundingInfo = sm.getBoundingInfo();
  50532. return {
  50533. position: idx,
  50534. verticesStart: sm.verticesStart,
  50535. verticesCount: sm.verticesCount,
  50536. indexStart: sm.indexStart,
  50537. indexCount: sm.indexCount,
  50538. hasMaterial: !!sm.getMaterial(),
  50539. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50540. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50541. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50542. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50543. };
  50544. });
  50545. }
  50546. var geometryId = null;
  50547. if (mesh instanceof BABYLON.Mesh) {
  50548. var geometry = mesh.geometry;
  50549. geometryId = geometry ? geometry.id : null;
  50550. }
  50551. else if (mesh instanceof BABYLON.InstancedMesh) {
  50552. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50553. geometryId = geometry ? geometry.id : null;
  50554. }
  50555. var boundingInfo = mesh.getBoundingInfo();
  50556. return {
  50557. uniqueId: mesh.uniqueId,
  50558. id: mesh.id,
  50559. name: mesh.name,
  50560. geometryId: geometryId,
  50561. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50562. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50563. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50564. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50565. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50566. subMeshes: submeshes,
  50567. checkCollisions: mesh.checkCollisions
  50568. };
  50569. };
  50570. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50571. return {
  50572. id: geometry.id,
  50573. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50574. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50575. indices: new Uint32Array(geometry.getIndices() || []),
  50576. };
  50577. };
  50578. return CollisionCoordinatorWorker;
  50579. }());
  50580. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50581. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50582. function CollisionCoordinatorLegacy() {
  50583. this._scaledPosition = BABYLON.Vector3.Zero();
  50584. this._scaledVelocity = BABYLON.Vector3.Zero();
  50585. this._finalPosition = BABYLON.Vector3.Zero();
  50586. }
  50587. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50588. position.divideToRef(collider._radius, this._scaledPosition);
  50589. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50590. collider.collidedMesh = null;
  50591. collider._retry = 0;
  50592. collider._initialVelocity = this._scaledVelocity;
  50593. collider._initialPosition = this._scaledPosition;
  50594. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50595. this._finalPosition.multiplyInPlace(collider._radius);
  50596. //run the callback
  50597. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50598. };
  50599. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50600. this._scene = scene;
  50601. };
  50602. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50603. //Legacy need no destruction method.
  50604. };
  50605. //No update in legacy mode
  50606. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50607. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50608. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50609. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50610. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50611. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50612. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50613. if (excludedMesh === void 0) { excludedMesh = null; }
  50614. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50615. if (collider._retry >= maximumRetry) {
  50616. finalPosition.copyFrom(position);
  50617. return;
  50618. }
  50619. // Check if this is a mesh else camera or -1
  50620. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50621. collider._initialize(position, velocity, closeDistance);
  50622. // Check all meshes
  50623. for (var index = 0; index < this._scene.meshes.length; index++) {
  50624. var mesh = this._scene.meshes[index];
  50625. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50626. mesh._checkCollision(collider);
  50627. }
  50628. }
  50629. if (!collider.collisionFound) {
  50630. position.addToRef(velocity, finalPosition);
  50631. return;
  50632. }
  50633. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50634. collider._getResponse(position, velocity);
  50635. }
  50636. if (velocity.length() <= closeDistance) {
  50637. finalPosition.copyFrom(position);
  50638. return;
  50639. }
  50640. collider._retry++;
  50641. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50642. };
  50643. return CollisionCoordinatorLegacy;
  50644. }());
  50645. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50646. })(BABYLON || (BABYLON = {}));
  50647. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50648. var BABYLON;
  50649. (function (BABYLON) {
  50650. /**
  50651. * A particle represents one of the element emitted by a particle system.
  50652. * This is mainly define by its coordinates, direction, velocity and age.
  50653. */
  50654. var Particle = /** @class */ (function () {
  50655. /**
  50656. * Creates a new instance of @see Particle
  50657. * @param particleSystem the particle system the particle belongs to
  50658. */
  50659. function Particle(
  50660. /**
  50661. * particleSystem the particle system the particle belongs to.
  50662. */
  50663. particleSystem) {
  50664. this.particleSystem = particleSystem;
  50665. /**
  50666. * The world position of the particle in the scene.
  50667. */
  50668. this.position = BABYLON.Vector3.Zero();
  50669. /**
  50670. * The world direction of the particle in the scene.
  50671. */
  50672. this.direction = BABYLON.Vector3.Zero();
  50673. /**
  50674. * The color of the particle.
  50675. */
  50676. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50677. /**
  50678. * The color change of the particle per step.
  50679. */
  50680. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50681. /**
  50682. * Defines how long will the life of the particle be.
  50683. */
  50684. this.lifeTime = 1.0;
  50685. /**
  50686. * The current age of the particle.
  50687. */
  50688. this.age = 0;
  50689. /**
  50690. * The current size of the particle.
  50691. */
  50692. this.size = 0;
  50693. /**
  50694. * The current angle of the particle.
  50695. */
  50696. this.angle = 0;
  50697. /**
  50698. * Defines how fast is the angle changing.
  50699. */
  50700. this.angularSpeed = 0;
  50701. /**
  50702. * Defines the cell index used by the particle to be rendered from a sprite.
  50703. */
  50704. this.cellIndex = 0;
  50705. this._currentFrameCounter = 0;
  50706. if (!this.particleSystem.isAnimationSheetEnabled) {
  50707. return;
  50708. }
  50709. this.updateCellInfoFromSystem();
  50710. }
  50711. Particle.prototype.updateCellInfoFromSystem = function () {
  50712. this.cellIndex = this.particleSystem.startSpriteCellID;
  50713. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50714. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50715. }
  50716. else {
  50717. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50718. }
  50719. };
  50720. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50721. // (ageOffset / scaledUpdateSpeed) / available cells
  50722. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50723. this._currentFrameCounter += scaledUpdateSpeed;
  50724. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50725. this._currentFrameCounter = 0;
  50726. this.cellIndex++;
  50727. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50728. this.cellIndex = this.particleSystem.endSpriteCellID;
  50729. }
  50730. }
  50731. };
  50732. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50733. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50734. this.cellIndex++;
  50735. this._currentFrameCounter = 0;
  50736. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50737. if (this.particleSystem.spriteCellLoop) {
  50738. this.cellIndex = this.particleSystem.startSpriteCellID;
  50739. }
  50740. else {
  50741. this.cellIndex = this.particleSystem.endSpriteCellID;
  50742. }
  50743. }
  50744. }
  50745. else {
  50746. this._currentFrameCounter++;
  50747. }
  50748. };
  50749. /**
  50750. * Copy the properties of particle to another one.
  50751. * @param other the particle to copy the information to.
  50752. */
  50753. Particle.prototype.copyTo = function (other) {
  50754. other.position.copyFrom(this.position);
  50755. other.direction.copyFrom(this.direction);
  50756. other.color.copyFrom(this.color);
  50757. other.colorStep.copyFrom(this.colorStep);
  50758. other.lifeTime = this.lifeTime;
  50759. other.age = this.age;
  50760. other.size = this.size;
  50761. other.angle = this.angle;
  50762. other.angularSpeed = this.angularSpeed;
  50763. other.particleSystem = this.particleSystem;
  50764. other.cellIndex = this.cellIndex;
  50765. };
  50766. return Particle;
  50767. }());
  50768. BABYLON.Particle = Particle;
  50769. })(BABYLON || (BABYLON = {}));
  50770. //# sourceMappingURL=babylon.particle.js.map
  50771. var BABYLON;
  50772. (function (BABYLON) {
  50773. /**
  50774. * This represents a particle system in Babylon.
  50775. * 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.
  50776. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50777. * @example https://doc.babylonjs.com/babylon101/particles
  50778. */
  50779. var ParticleSystem = /** @class */ (function () {
  50780. /**
  50781. * Instantiates a particle system.
  50782. * 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.
  50783. * @param name The name of the particle system
  50784. * @param capacity The max number of particles alive at the same time
  50785. * @param scene The scene the particle system belongs to
  50786. * @param customEffect a custom effect used to change the way particles are rendered by default
  50787. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50788. * @param epsilon Offset used to render the particles
  50789. */
  50790. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50791. if (customEffect === void 0) { customEffect = null; }
  50792. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50793. if (epsilon === void 0) { epsilon = 0.01; }
  50794. var _this = this;
  50795. /**
  50796. * List of animations used by the particle system.
  50797. */
  50798. this.animations = [];
  50799. /**
  50800. * The rendering group used by the Particle system to chose when to render.
  50801. */
  50802. this.renderingGroupId = 0;
  50803. /**
  50804. * The emitter represents the Mesh or position we are attaching the particle system to.
  50805. */
  50806. this.emitter = null;
  50807. /**
  50808. * The maximum number of particles to emit per frame
  50809. */
  50810. this.emitRate = 10;
  50811. /**
  50812. * If you want to launch only a few particles at once, that can be done, as well.
  50813. */
  50814. this.manualEmitCount = -1;
  50815. /**
  50816. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50817. */
  50818. this.updateSpeed = 0.01;
  50819. /**
  50820. * The amount of time the particle system is running (depends of the overall update speed).
  50821. */
  50822. this.targetStopDuration = 0;
  50823. /**
  50824. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50825. */
  50826. this.disposeOnStop = false;
  50827. /**
  50828. * Minimum power of emitting particles.
  50829. */
  50830. this.minEmitPower = 1;
  50831. /**
  50832. * Maximum power of emitting particles.
  50833. */
  50834. this.maxEmitPower = 1;
  50835. /**
  50836. * Minimum life time of emitting particles.
  50837. */
  50838. this.minLifeTime = 1;
  50839. /**
  50840. * Maximum life time of emitting particles.
  50841. */
  50842. this.maxLifeTime = 1;
  50843. /**
  50844. * Minimum Size of emitting particles.
  50845. */
  50846. this.minSize = 1;
  50847. /**
  50848. * Maximum Size of emitting particles.
  50849. */
  50850. this.maxSize = 1;
  50851. /**
  50852. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50853. */
  50854. this.minAngularSpeed = 0;
  50855. /**
  50856. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50857. */
  50858. this.maxAngularSpeed = 0;
  50859. /**
  50860. * The layer mask we are rendering the particles through.
  50861. */
  50862. this.layerMask = 0x0FFFFFFF;
  50863. /**
  50864. * This can help using your own shader to render the particle system.
  50865. * The according effect will be created
  50866. */
  50867. this.customShader = null;
  50868. /**
  50869. * By default particle system starts as soon as they are created. This prevents the
  50870. * automatic start to happen and let you decide when to start emitting particles.
  50871. */
  50872. this.preventAutoStart = false;
  50873. /**
  50874. * Callback triggered when the particle animation is ending.
  50875. */
  50876. this.onAnimationEnd = null;
  50877. /**
  50878. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50879. */
  50880. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50881. /**
  50882. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50883. * to override the particles.
  50884. */
  50885. this.forceDepthWrite = false;
  50886. /**
  50887. * You can use gravity if you want to give an orientation to your particles.
  50888. */
  50889. this.gravity = BABYLON.Vector3.Zero();
  50890. /**
  50891. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50892. */
  50893. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50894. /**
  50895. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50896. */
  50897. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50898. /**
  50899. * Color the particle will have at the end of its lifetime.
  50900. */
  50901. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50902. /**
  50903. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50904. */
  50905. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50906. /**
  50907. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50908. */
  50909. this.spriteCellLoop = true;
  50910. /**
  50911. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50912. */
  50913. this.spriteCellChangeSpeed = 0;
  50914. /**
  50915. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50916. */
  50917. this.startSpriteCellID = 0;
  50918. /**
  50919. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50920. */
  50921. this.endSpriteCellID = 0;
  50922. /**
  50923. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50924. */
  50925. this.spriteCellWidth = 0;
  50926. /**
  50927. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50928. */
  50929. this.spriteCellHeight = 0;
  50930. /**
  50931. * An event triggered when the system is disposed.
  50932. */
  50933. this.onDisposeObservable = new BABYLON.Observable();
  50934. this._particles = new Array();
  50935. this._stockParticles = new Array();
  50936. this._newPartsExcess = 0;
  50937. this._vertexBuffers = {};
  50938. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50939. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50940. this._scaledDirection = BABYLON.Vector3.Zero();
  50941. this._scaledGravity = BABYLON.Vector3.Zero();
  50942. this._currentRenderId = -1;
  50943. this._started = false;
  50944. this._stopped = false;
  50945. this._actualFrame = 0;
  50946. this._vertexBufferSize = 11;
  50947. // start of sub system methods
  50948. /**
  50949. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50950. * Its lifetime will start back at 0.
  50951. */
  50952. this.recycleParticle = function (particle) {
  50953. var lastParticle = _this._particles.pop();
  50954. if (lastParticle !== particle) {
  50955. lastParticle.copyTo(particle);
  50956. }
  50957. _this._stockParticles.push(lastParticle);
  50958. };
  50959. this._createParticle = function () {
  50960. var particle;
  50961. if (_this._stockParticles.length !== 0) {
  50962. particle = _this._stockParticles.pop();
  50963. particle.age = 0;
  50964. particle.cellIndex = _this.startSpriteCellID;
  50965. }
  50966. else {
  50967. particle = new BABYLON.Particle(_this);
  50968. }
  50969. return particle;
  50970. };
  50971. this._emitFromParticle = function (particle) {
  50972. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  50973. return;
  50974. }
  50975. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  50976. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  50977. subSystem._rootParticleSystem = _this;
  50978. _this.activeSubSystems.push(subSystem);
  50979. subSystem.start();
  50980. };
  50981. this._appendParticleVertexes = null;
  50982. this.id = name;
  50983. this.name = name;
  50984. this._capacity = capacity;
  50985. this._epsilon = epsilon;
  50986. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50987. if (isAnimationSheetEnabled) {
  50988. this._vertexBufferSize = 12;
  50989. }
  50990. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50991. this._customEffect = customEffect;
  50992. scene.particleSystems.push(this);
  50993. this._createIndexBuffer();
  50994. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50995. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50996. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50997. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50998. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50999. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51000. if (this._isAnimationSheetEnabled) {
  51001. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51002. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51003. }
  51004. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51005. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51006. this._vertexBuffers["options"] = options;
  51007. // Default emitter type
  51008. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51009. this.updateFunction = function (particles) {
  51010. for (var index = 0; index < particles.length; index++) {
  51011. var particle = particles[index];
  51012. particle.age += _this._scaledUpdateSpeed;
  51013. if (particle.age >= particle.lifeTime) {
  51014. _this._emitFromParticle(particle);
  51015. _this.recycleParticle(particle);
  51016. index--;
  51017. continue;
  51018. }
  51019. else {
  51020. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51021. particle.color.addInPlace(_this._scaledColorStep);
  51022. if (particle.color.a < 0)
  51023. particle.color.a = 0;
  51024. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51025. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51026. particle.position.addInPlace(_this._scaledDirection);
  51027. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51028. particle.direction.addInPlace(_this._scaledGravity);
  51029. if (_this._isAnimationSheetEnabled) {
  51030. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51031. }
  51032. }
  51033. }
  51034. };
  51035. }
  51036. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51037. /**
  51038. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51039. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51040. */
  51041. get: function () {
  51042. if (this.particleEmitterType.direction1) {
  51043. return this.particleEmitterType.direction1;
  51044. }
  51045. return BABYLON.Vector3.Zero();
  51046. },
  51047. set: function (value) {
  51048. if (this.particleEmitterType.direction1) {
  51049. this.particleEmitterType.direction1 = value;
  51050. }
  51051. },
  51052. enumerable: true,
  51053. configurable: true
  51054. });
  51055. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51056. /**
  51057. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51058. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51059. */
  51060. get: function () {
  51061. if (this.particleEmitterType.direction2) {
  51062. return this.particleEmitterType.direction2;
  51063. }
  51064. return BABYLON.Vector3.Zero();
  51065. },
  51066. set: function (value) {
  51067. if (this.particleEmitterType.direction2) {
  51068. this.particleEmitterType.direction2 = value;
  51069. }
  51070. },
  51071. enumerable: true,
  51072. configurable: true
  51073. });
  51074. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51075. /**
  51076. * 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.
  51077. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51078. */
  51079. get: function () {
  51080. if (this.particleEmitterType.minEmitBox) {
  51081. return this.particleEmitterType.minEmitBox;
  51082. }
  51083. return BABYLON.Vector3.Zero();
  51084. },
  51085. set: function (value) {
  51086. if (this.particleEmitterType.minEmitBox) {
  51087. this.particleEmitterType.minEmitBox = value;
  51088. }
  51089. },
  51090. enumerable: true,
  51091. configurable: true
  51092. });
  51093. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51094. /**
  51095. * 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.
  51096. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51097. */
  51098. get: function () {
  51099. if (this.particleEmitterType.maxEmitBox) {
  51100. return this.particleEmitterType.maxEmitBox;
  51101. }
  51102. return BABYLON.Vector3.Zero();
  51103. },
  51104. set: function (value) {
  51105. if (this.particleEmitterType.maxEmitBox) {
  51106. this.particleEmitterType.maxEmitBox = value;
  51107. }
  51108. },
  51109. enumerable: true,
  51110. configurable: true
  51111. });
  51112. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51113. /**
  51114. * Sets a callback that will be triggered when the system is disposed.
  51115. */
  51116. set: function (callback) {
  51117. if (this._onDisposeObserver) {
  51118. this.onDisposeObservable.remove(this._onDisposeObserver);
  51119. }
  51120. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51121. },
  51122. enumerable: true,
  51123. configurable: true
  51124. });
  51125. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51126. /**
  51127. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51128. */
  51129. get: function () {
  51130. return this._isAnimationSheetEnabled;
  51131. },
  51132. enumerable: true,
  51133. configurable: true
  51134. });
  51135. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51136. //end of Sub-emitter
  51137. /**
  51138. * Gets the current list of active particles
  51139. */
  51140. get: function () {
  51141. return this._particles;
  51142. },
  51143. enumerable: true,
  51144. configurable: true
  51145. });
  51146. /**
  51147. * Returns the string "ParticleSystem"
  51148. * @returns a string containing the class name
  51149. */
  51150. ParticleSystem.prototype.getClassName = function () {
  51151. return "ParticleSystem";
  51152. };
  51153. ParticleSystem.prototype._createIndexBuffer = function () {
  51154. var indices = [];
  51155. var index = 0;
  51156. for (var count = 0; count < this._capacity; count++) {
  51157. indices.push(index);
  51158. indices.push(index + 1);
  51159. indices.push(index + 2);
  51160. indices.push(index);
  51161. indices.push(index + 2);
  51162. indices.push(index + 3);
  51163. index += 4;
  51164. }
  51165. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51166. };
  51167. /**
  51168. * Gets the maximum number of particles active at the same time.
  51169. * @returns The max number of active particles.
  51170. */
  51171. ParticleSystem.prototype.getCapacity = function () {
  51172. return this._capacity;
  51173. };
  51174. /**
  51175. * Gets Wether there are still active particles in the system.
  51176. * @returns True if it is alive, otherwise false.
  51177. */
  51178. ParticleSystem.prototype.isAlive = function () {
  51179. return this._alive;
  51180. };
  51181. /**
  51182. * Gets Wether the system has been started.
  51183. * @returns True if it has been started, otherwise false.
  51184. */
  51185. ParticleSystem.prototype.isStarted = function () {
  51186. return this._started;
  51187. };
  51188. /**
  51189. * Starts the particle system and begins to emit.
  51190. */
  51191. ParticleSystem.prototype.start = function () {
  51192. this._started = true;
  51193. this._stopped = false;
  51194. this._actualFrame = 0;
  51195. if (this.subEmitters && this.subEmitters.length != 0) {
  51196. this.activeSubSystems = new Array();
  51197. }
  51198. };
  51199. /**
  51200. * Stops the particle system.
  51201. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51202. */
  51203. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51204. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51205. this._stopped = true;
  51206. if (stopSubEmitters) {
  51207. this._stopSubEmitters();
  51208. }
  51209. };
  51210. // animation sheet
  51211. /**
  51212. * Remove all active particles
  51213. */
  51214. ParticleSystem.prototype.reset = function () {
  51215. this._stockParticles = [];
  51216. this._particles = [];
  51217. };
  51218. /**
  51219. * @ignore (for internal use only)
  51220. */
  51221. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51222. var offset = index * this._vertexBufferSize;
  51223. this._vertexData[offset] = particle.position.x;
  51224. this._vertexData[offset + 1] = particle.position.y;
  51225. this._vertexData[offset + 2] = particle.position.z;
  51226. this._vertexData[offset + 3] = particle.color.r;
  51227. this._vertexData[offset + 4] = particle.color.g;
  51228. this._vertexData[offset + 5] = particle.color.b;
  51229. this._vertexData[offset + 6] = particle.color.a;
  51230. this._vertexData[offset + 7] = particle.angle;
  51231. this._vertexData[offset + 8] = particle.size;
  51232. this._vertexData[offset + 9] = offsetX;
  51233. this._vertexData[offset + 10] = offsetY;
  51234. };
  51235. /**
  51236. * @ignore (for internal use only)
  51237. */
  51238. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51239. if (offsetX === 0)
  51240. offsetX = this._epsilon;
  51241. else if (offsetX === 1)
  51242. offsetX = 1 - this._epsilon;
  51243. if (offsetY === 0)
  51244. offsetY = this._epsilon;
  51245. else if (offsetY === 1)
  51246. offsetY = 1 - this._epsilon;
  51247. var offset = index * this._vertexBufferSize;
  51248. this._vertexData[offset] = particle.position.x;
  51249. this._vertexData[offset + 1] = particle.position.y;
  51250. this._vertexData[offset + 2] = particle.position.z;
  51251. this._vertexData[offset + 3] = particle.color.r;
  51252. this._vertexData[offset + 4] = particle.color.g;
  51253. this._vertexData[offset + 5] = particle.color.b;
  51254. this._vertexData[offset + 6] = particle.color.a;
  51255. this._vertexData[offset + 7] = particle.angle;
  51256. this._vertexData[offset + 8] = particle.size;
  51257. this._vertexData[offset + 9] = offsetX;
  51258. this._vertexData[offset + 10] = offsetY;
  51259. this._vertexData[offset + 11] = particle.cellIndex;
  51260. };
  51261. ParticleSystem.prototype._stopSubEmitters = function () {
  51262. if (!this.activeSubSystems) {
  51263. return;
  51264. }
  51265. this.activeSubSystems.forEach(function (subSystem) {
  51266. subSystem.stop(true);
  51267. });
  51268. this.activeSubSystems = new Array();
  51269. };
  51270. ParticleSystem.prototype._removeFromRoot = function () {
  51271. if (!this._rootParticleSystem) {
  51272. return;
  51273. }
  51274. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51275. if (index !== -1) {
  51276. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51277. }
  51278. };
  51279. // end of sub system methods
  51280. ParticleSystem.prototype._update = function (newParticles) {
  51281. // Update current
  51282. this._alive = this._particles.length > 0;
  51283. this.updateFunction(this._particles);
  51284. // Add new ones
  51285. var worldMatrix;
  51286. if (this.emitter.position) {
  51287. var emitterMesh = this.emitter;
  51288. worldMatrix = emitterMesh.getWorldMatrix();
  51289. }
  51290. else {
  51291. var emitterPosition = this.emitter;
  51292. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51293. }
  51294. var particle;
  51295. for (var index = 0; index < newParticles; index++) {
  51296. if (this._particles.length === this._capacity) {
  51297. break;
  51298. }
  51299. particle = this._createParticle();
  51300. this._particles.push(particle);
  51301. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51302. if (this.startPositionFunction) {
  51303. this.startPositionFunction(worldMatrix, particle.position, particle);
  51304. }
  51305. else {
  51306. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51307. }
  51308. if (this.startDirectionFunction) {
  51309. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51310. }
  51311. else {
  51312. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51313. }
  51314. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51315. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51316. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51317. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51318. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51319. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51320. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51321. }
  51322. };
  51323. ParticleSystem.prototype._getEffect = function () {
  51324. if (this._customEffect) {
  51325. return this._customEffect;
  51326. }
  51327. ;
  51328. var defines = [];
  51329. if (this._scene.clipPlane) {
  51330. defines.push("#define CLIPPLANE");
  51331. }
  51332. if (this._isAnimationSheetEnabled) {
  51333. defines.push("#define ANIMATESHEET");
  51334. }
  51335. // Effect
  51336. var join = defines.join("\n");
  51337. if (this._cachedDefines !== join) {
  51338. this._cachedDefines = join;
  51339. var attributesNamesOrOptions;
  51340. var effectCreationOption;
  51341. if (this._isAnimationSheetEnabled) {
  51342. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51343. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51344. }
  51345. else {
  51346. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51347. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51348. }
  51349. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51350. }
  51351. return this._effect;
  51352. };
  51353. /**
  51354. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51355. */
  51356. ParticleSystem.prototype.animate = function () {
  51357. if (!this._started)
  51358. return;
  51359. var effect = this._getEffect();
  51360. // Check
  51361. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51362. return;
  51363. if (this._currentRenderId === this._scene.getRenderId()) {
  51364. return;
  51365. }
  51366. this._currentRenderId = this._scene.getRenderId();
  51367. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51368. // determine the number of particles we need to create
  51369. var newParticles;
  51370. if (this.manualEmitCount > -1) {
  51371. newParticles = this.manualEmitCount;
  51372. this._newPartsExcess = 0;
  51373. this.manualEmitCount = 0;
  51374. }
  51375. else {
  51376. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51377. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51378. }
  51379. if (this._newPartsExcess > 1.0) {
  51380. newParticles += this._newPartsExcess >> 0;
  51381. this._newPartsExcess -= this._newPartsExcess >> 0;
  51382. }
  51383. this._alive = false;
  51384. if (!this._stopped) {
  51385. this._actualFrame += this._scaledUpdateSpeed;
  51386. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51387. this.stop();
  51388. }
  51389. else {
  51390. newParticles = 0;
  51391. }
  51392. this._update(newParticles);
  51393. // Stopped?
  51394. if (this._stopped) {
  51395. if (!this._alive) {
  51396. this._started = false;
  51397. if (this.onAnimationEnd) {
  51398. this.onAnimationEnd();
  51399. }
  51400. if (this.disposeOnStop) {
  51401. this._scene._toBeDisposed.push(this);
  51402. }
  51403. }
  51404. }
  51405. // Animation sheet
  51406. if (this._isAnimationSheetEnabled) {
  51407. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51408. }
  51409. else {
  51410. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51411. }
  51412. // Update VBO
  51413. var offset = 0;
  51414. for (var index = 0; index < this._particles.length; index++) {
  51415. var particle = this._particles[index];
  51416. this._appendParticleVertexes(offset, particle);
  51417. offset += 4;
  51418. }
  51419. if (this._vertexBuffer) {
  51420. this._vertexBuffer.update(this._vertexData);
  51421. }
  51422. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51423. this.stop();
  51424. }
  51425. };
  51426. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51427. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51428. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51429. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51430. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51431. };
  51432. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51433. this._appendParticleVertex(offset++, particle, 0, 0);
  51434. this._appendParticleVertex(offset++, particle, 1, 0);
  51435. this._appendParticleVertex(offset++, particle, 1, 1);
  51436. this._appendParticleVertex(offset++, particle, 0, 1);
  51437. };
  51438. /**
  51439. * Rebuilds the particle system.
  51440. */
  51441. ParticleSystem.prototype.rebuild = function () {
  51442. this._createIndexBuffer();
  51443. if (this._vertexBuffer) {
  51444. this._vertexBuffer._rebuild();
  51445. }
  51446. };
  51447. /**
  51448. * Is this system ready to be used/rendered
  51449. * @return true if the system is ready
  51450. */
  51451. ParticleSystem.prototype.isReady = function () {
  51452. var effect = this._getEffect();
  51453. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  51454. return false;
  51455. }
  51456. return true;
  51457. };
  51458. /**
  51459. * Renders the particle system in its current state.
  51460. * @returns the current number of particles
  51461. */
  51462. ParticleSystem.prototype.render = function () {
  51463. var effect = this._getEffect();
  51464. // Check
  51465. if (!this.isReady() || !this._particles.length) {
  51466. return 0;
  51467. }
  51468. var engine = this._scene.getEngine();
  51469. // Render
  51470. engine.enableEffect(effect);
  51471. engine.setState(false);
  51472. var viewMatrix = this._scene.getViewMatrix();
  51473. effect.setTexture("diffuseSampler", this.particleTexture);
  51474. effect.setMatrix("view", viewMatrix);
  51475. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51476. if (this._isAnimationSheetEnabled && this.particleTexture) {
  51477. var baseSize = this.particleTexture.getBaseSize();
  51478. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51479. }
  51480. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51481. if (this._scene.clipPlane) {
  51482. var clipPlane = this._scene.clipPlane;
  51483. var invView = viewMatrix.clone();
  51484. invView.invert();
  51485. effect.setMatrix("invView", invView);
  51486. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51487. }
  51488. // VBOs
  51489. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51490. // Draw order
  51491. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51492. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51493. }
  51494. else {
  51495. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51496. }
  51497. if (this.forceDepthWrite) {
  51498. engine.setDepthWrite(true);
  51499. }
  51500. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51501. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51502. return this._particles.length;
  51503. };
  51504. /**
  51505. * Disposes the particle system and free the associated resources
  51506. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51507. */
  51508. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51509. if (disposeTexture === void 0) { disposeTexture = true; }
  51510. if (this._vertexBuffer) {
  51511. this._vertexBuffer.dispose();
  51512. this._vertexBuffer = null;
  51513. }
  51514. if (this._indexBuffer) {
  51515. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51516. this._indexBuffer = null;
  51517. }
  51518. if (disposeTexture && this.particleTexture) {
  51519. this.particleTexture.dispose();
  51520. this.particleTexture = null;
  51521. }
  51522. this._removeFromRoot();
  51523. // Remove from scene
  51524. var index = this._scene.particleSystems.indexOf(this);
  51525. if (index > -1) {
  51526. this._scene.particleSystems.splice(index, 1);
  51527. }
  51528. // Callback
  51529. this.onDisposeObservable.notifyObservers(this);
  51530. this.onDisposeObservable.clear();
  51531. };
  51532. /**
  51533. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51534. * @param radius The radius of the sphere to emit from
  51535. * @returns the emitter
  51536. */
  51537. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51538. if (radius === void 0) { radius = 1; }
  51539. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51540. this.particleEmitterType = particleEmitter;
  51541. return particleEmitter;
  51542. };
  51543. /**
  51544. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51545. * @param radius The radius of the sphere to emit from
  51546. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51547. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51548. * @returns the emitter
  51549. */
  51550. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51551. if (radius === void 0) { radius = 1; }
  51552. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51553. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51554. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51555. this.particleEmitterType = particleEmitter;
  51556. return particleEmitter;
  51557. };
  51558. /**
  51559. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51560. * @param radius The radius of the cone to emit from
  51561. * @param angle The base angle of the cone
  51562. * @returns the emitter
  51563. */
  51564. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51565. if (radius === void 0) { radius = 1; }
  51566. if (angle === void 0) { angle = Math.PI / 4; }
  51567. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51568. this.particleEmitterType = particleEmitter;
  51569. return particleEmitter;
  51570. };
  51571. // 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.
  51572. /**
  51573. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51574. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51575. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51576. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51577. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51578. * @returns the emitter
  51579. */
  51580. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51581. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51582. this.direction1 = direction1;
  51583. this.direction2 = direction2;
  51584. this.minEmitBox = minEmitBox;
  51585. this.maxEmitBox = maxEmitBox;
  51586. this.particleEmitterType = particleEmitter;
  51587. return particleEmitter;
  51588. };
  51589. // Clone
  51590. /**
  51591. * Clones the particle system.
  51592. * @param name The name of the cloned object
  51593. * @param newEmitter The new emitter to use
  51594. * @returns the cloned particle system
  51595. */
  51596. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51597. var custom = null;
  51598. var program = null;
  51599. if (this.customShader != null) {
  51600. program = this.customShader;
  51601. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51602. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51603. }
  51604. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51605. result.customShader = program;
  51606. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51607. if (newEmitter === undefined) {
  51608. newEmitter = this.emitter;
  51609. }
  51610. result.emitter = newEmitter;
  51611. if (this.particleTexture) {
  51612. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51613. }
  51614. if (!this.preventAutoStart) {
  51615. result.start();
  51616. }
  51617. return result;
  51618. };
  51619. /**
  51620. * Serializes the particle system to a JSON object.
  51621. * @returns the JSON object
  51622. */
  51623. ParticleSystem.prototype.serialize = function () {
  51624. var serializationObject = {};
  51625. serializationObject.name = this.name;
  51626. serializationObject.id = this.id;
  51627. // Emitter
  51628. if (this.emitter.position) {
  51629. var emitterMesh = this.emitter;
  51630. serializationObject.emitterId = emitterMesh.id;
  51631. }
  51632. else {
  51633. var emitterPosition = this.emitter;
  51634. serializationObject.emitter = emitterPosition.asArray();
  51635. }
  51636. serializationObject.capacity = this.getCapacity();
  51637. if (this.particleTexture) {
  51638. serializationObject.textureName = this.particleTexture.name;
  51639. }
  51640. // Animations
  51641. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51642. // Particle system
  51643. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51644. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51645. serializationObject.minSize = this.minSize;
  51646. serializationObject.maxSize = this.maxSize;
  51647. serializationObject.minEmitPower = this.minEmitPower;
  51648. serializationObject.maxEmitPower = this.maxEmitPower;
  51649. serializationObject.minLifeTime = this.minLifeTime;
  51650. serializationObject.maxLifeTime = this.maxLifeTime;
  51651. serializationObject.emitRate = this.emitRate;
  51652. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51653. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51654. serializationObject.gravity = this.gravity.asArray();
  51655. serializationObject.direction1 = this.direction1.asArray();
  51656. serializationObject.direction2 = this.direction2.asArray();
  51657. serializationObject.color1 = this.color1.asArray();
  51658. serializationObject.color2 = this.color2.asArray();
  51659. serializationObject.colorDead = this.colorDead.asArray();
  51660. serializationObject.updateSpeed = this.updateSpeed;
  51661. serializationObject.targetStopDuration = this.targetStopDuration;
  51662. serializationObject.textureMask = this.textureMask.asArray();
  51663. serializationObject.blendMode = this.blendMode;
  51664. serializationObject.customShader = this.customShader;
  51665. serializationObject.preventAutoStart = this.preventAutoStart;
  51666. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51667. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51668. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51669. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51670. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51671. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51672. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51673. // Emitter
  51674. if (this.particleEmitterType) {
  51675. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51676. }
  51677. return serializationObject;
  51678. };
  51679. /**
  51680. * Parses a JSON object to create a particle system.
  51681. * @param parsedParticleSystem The JSON object to parse
  51682. * @param scene The scene to create the particle system in
  51683. * @param rootUrl The root url to use to load external dependencies like texture
  51684. * @returns the Parsed particle system
  51685. */
  51686. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51687. var name = parsedParticleSystem.name;
  51688. var custom = null;
  51689. var program = null;
  51690. if (parsedParticleSystem.customShader) {
  51691. program = parsedParticleSystem.customShader;
  51692. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51693. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51694. }
  51695. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51696. particleSystem.customShader = program;
  51697. if (parsedParticleSystem.id) {
  51698. particleSystem.id = parsedParticleSystem.id;
  51699. }
  51700. // Auto start
  51701. if (parsedParticleSystem.preventAutoStart) {
  51702. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51703. }
  51704. // Texture
  51705. if (parsedParticleSystem.textureName) {
  51706. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51707. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51708. }
  51709. // Emitter
  51710. if (parsedParticleSystem.emitterId) {
  51711. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51712. }
  51713. else {
  51714. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51715. }
  51716. // Animations
  51717. if (parsedParticleSystem.animations) {
  51718. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51719. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51720. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51721. }
  51722. }
  51723. if (parsedParticleSystem.autoAnimate) {
  51724. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51725. }
  51726. // Particle system
  51727. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51728. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51729. particleSystem.minSize = parsedParticleSystem.minSize;
  51730. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51731. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51732. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51733. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51734. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51735. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51736. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51737. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51738. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51739. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51740. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51741. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51742. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51743. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51744. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51745. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51746. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51747. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51748. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51749. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51750. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51751. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51752. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51753. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51754. if (!particleSystem.preventAutoStart) {
  51755. particleSystem.start();
  51756. }
  51757. return particleSystem;
  51758. };
  51759. /**
  51760. * Source color is added to the destination color without alpha affecting the result.
  51761. */
  51762. ParticleSystem.BLENDMODE_ONEONE = 0;
  51763. /**
  51764. * Blend current color and particle color using particle’s alpha.
  51765. */
  51766. ParticleSystem.BLENDMODE_STANDARD = 1;
  51767. return ParticleSystem;
  51768. }());
  51769. BABYLON.ParticleSystem = ParticleSystem;
  51770. })(BABYLON || (BABYLON = {}));
  51771. //# sourceMappingURL=babylon.particleSystem.js.map
  51772. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51773. var BABYLON;
  51774. (function (BABYLON) {
  51775. /**
  51776. * Particle emitter emitting particles from the inside of a box.
  51777. * It emits the particles randomly between 2 given directions.
  51778. */
  51779. var BoxParticleEmitter = /** @class */ (function () {
  51780. /**
  51781. * Creates a new instance of @see BoxParticleEmitter
  51782. */
  51783. function BoxParticleEmitter() {
  51784. /**
  51785. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51786. */
  51787. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51788. /**
  51789. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51790. */
  51791. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51792. /**
  51793. * 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.
  51794. */
  51795. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51796. /**
  51797. * 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.
  51798. */
  51799. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51800. }
  51801. /**
  51802. * Called by the particle System when the direction is computed for the created particle.
  51803. * @param emitPower is the power of the particle (speed)
  51804. * @param worldMatrix is the world matrix of the particle system
  51805. * @param directionToUpdate is the direction vector to update with the result
  51806. * @param particle is the particle we are computed the direction for
  51807. */
  51808. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51809. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51810. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51811. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51812. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51813. };
  51814. /**
  51815. * Called by the particle System when the position is computed for the created particle.
  51816. * @param worldMatrix is the world matrix of the particle system
  51817. * @param positionToUpdate is the position vector to update with the result
  51818. * @param particle is the particle we are computed the position for
  51819. */
  51820. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51821. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51822. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51823. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51825. };
  51826. /**
  51827. * Clones the current emitter and returns a copy of it
  51828. * @returns the new emitter
  51829. */
  51830. BoxParticleEmitter.prototype.clone = function () {
  51831. var newOne = new BoxParticleEmitter();
  51832. BABYLON.Tools.DeepCopy(this, newOne);
  51833. return newOne;
  51834. };
  51835. /**
  51836. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51837. * @param effect defines the update shader
  51838. */
  51839. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51840. effect.setVector3("direction1", this.direction1);
  51841. effect.setVector3("direction2", this.direction2);
  51842. effect.setVector3("minEmitBox", this.minEmitBox);
  51843. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51844. };
  51845. /**
  51846. * Returns a string to use to update the GPU particles update shader
  51847. * @returns a string containng the defines string
  51848. */
  51849. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51850. return "#define BOXEMITTER";
  51851. };
  51852. /**
  51853. * Returns the string "BoxEmitter"
  51854. * @returns a string containing the class name
  51855. */
  51856. BoxParticleEmitter.prototype.getClassName = function () {
  51857. return "BoxEmitter";
  51858. };
  51859. /**
  51860. * Serializes the particle system to a JSON object.
  51861. * @returns the JSON object
  51862. */
  51863. BoxParticleEmitter.prototype.serialize = function () {
  51864. var serializationObject = {};
  51865. serializationObject.type = this.getClassName();
  51866. serializationObject.direction1 = this.direction1.asArray();
  51867. ;
  51868. serializationObject.direction2 = this.direction2.asArray();
  51869. ;
  51870. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51871. ;
  51872. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51873. ;
  51874. return serializationObject;
  51875. };
  51876. /**
  51877. * Parse properties from a JSON object
  51878. * @param serializationObject defines the JSON object
  51879. */
  51880. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51881. this.direction1.copyFrom(serializationObject.direction1);
  51882. this.direction2.copyFrom(serializationObject.direction2);
  51883. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51884. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51885. };
  51886. return BoxParticleEmitter;
  51887. }());
  51888. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51889. })(BABYLON || (BABYLON = {}));
  51890. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51891. var BABYLON;
  51892. (function (BABYLON) {
  51893. /**
  51894. * Particle emitter emitting particles from the inside of a cone.
  51895. * It emits the particles alongside the cone volume from the base to the particle.
  51896. * The emission direction might be randomized.
  51897. */
  51898. var ConeParticleEmitter = /** @class */ (function () {
  51899. /**
  51900. * Creates a new instance of @see ConeParticleEmitter
  51901. * @param radius the radius of the emission cone (1 by default)
  51902. * @param angles the cone base angle (PI by default)
  51903. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51904. */
  51905. function ConeParticleEmitter(radius,
  51906. /**
  51907. * The radius of the emission cone.
  51908. */
  51909. angle,
  51910. /**
  51911. * The cone base angle.
  51912. */
  51913. directionRandomizer) {
  51914. if (radius === void 0) { radius = 1; }
  51915. if (angle === void 0) { angle = Math.PI; }
  51916. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51917. this.angle = angle;
  51918. this.directionRandomizer = directionRandomizer;
  51919. this.radius = radius;
  51920. }
  51921. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51922. /**
  51923. * Gets the radius of the emission cone.
  51924. */
  51925. get: function () {
  51926. return this._radius;
  51927. },
  51928. /**
  51929. * Sets the radius of the emission cone.
  51930. */
  51931. set: function (value) {
  51932. this._radius = value;
  51933. if (this.angle !== 0) {
  51934. this._height = value / Math.tan(this.angle / 2);
  51935. }
  51936. else {
  51937. this._height = 1;
  51938. }
  51939. },
  51940. enumerable: true,
  51941. configurable: true
  51942. });
  51943. /**
  51944. * Called by the particle System when the direction is computed for the created particle.
  51945. * @param emitPower is the power of the particle (speed)
  51946. * @param worldMatrix is the world matrix of the particle system
  51947. * @param directionToUpdate is the direction vector to update with the result
  51948. * @param particle is the particle we are computed the direction for
  51949. */
  51950. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51951. if (this.angle === 0) {
  51952. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51953. }
  51954. else {
  51955. // measure the direction Vector from the emitter to the particle.
  51956. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51957. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51958. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51959. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51960. direction.x += randX;
  51961. direction.y += randY;
  51962. direction.z += randZ;
  51963. direction.normalize();
  51964. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51965. }
  51966. };
  51967. /**
  51968. * Called by the particle System when the position is computed for the created particle.
  51969. * @param worldMatrix is the world matrix of the particle system
  51970. * @param positionToUpdate is the position vector to update with the result
  51971. * @param particle is the particle we are computed the position for
  51972. */
  51973. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51974. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51975. var h = BABYLON.Scalar.RandomRange(0, 1);
  51976. // Better distribution in a cone at normal angles.
  51977. h = 1 - h * h;
  51978. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51979. radius = radius * h / this._height;
  51980. var randX = radius * Math.sin(s);
  51981. var randZ = radius * Math.cos(s);
  51982. var randY = h * this._height;
  51983. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51984. };
  51985. /**
  51986. * Clones the current emitter and returns a copy of it
  51987. * @returns the new emitter
  51988. */
  51989. ConeParticleEmitter.prototype.clone = function () {
  51990. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51991. BABYLON.Tools.DeepCopy(this, newOne);
  51992. return newOne;
  51993. };
  51994. /**
  51995. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51996. * @param effect defines the update shader
  51997. */
  51998. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51999. effect.setFloat("radius", this.radius);
  52000. effect.setFloat("angle", this.angle);
  52001. effect.setFloat("height", this._height);
  52002. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52003. };
  52004. /**
  52005. * Returns a string to use to update the GPU particles update shader
  52006. * @returns a string containng the defines string
  52007. */
  52008. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52009. return "#define CONEEMITTER";
  52010. };
  52011. /**
  52012. * Returns the string "BoxEmitter"
  52013. * @returns a string containing the class name
  52014. */
  52015. ConeParticleEmitter.prototype.getClassName = function () {
  52016. return "ConeEmitter";
  52017. };
  52018. /**
  52019. * Serializes the particle system to a JSON object.
  52020. * @returns the JSON object
  52021. */
  52022. ConeParticleEmitter.prototype.serialize = function () {
  52023. var serializationObject = {};
  52024. serializationObject.type = this.getClassName();
  52025. serializationObject.radius = this.radius;
  52026. serializationObject.angle = this.angle;
  52027. serializationObject.directionRandomizer = this.directionRandomizer;
  52028. return serializationObject;
  52029. };
  52030. /**
  52031. * Parse properties from a JSON object
  52032. * @param serializationObject defines the JSON object
  52033. */
  52034. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52035. this.radius = serializationObject.radius;
  52036. this.angle = serializationObject.angle;
  52037. this.directionRandomizer = serializationObject.directionRandomizer;
  52038. };
  52039. return ConeParticleEmitter;
  52040. }());
  52041. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52042. })(BABYLON || (BABYLON = {}));
  52043. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52044. var BABYLON;
  52045. (function (BABYLON) {
  52046. /**
  52047. * Particle emitter emitting particles from the inside of a sphere.
  52048. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52049. */
  52050. var SphereParticleEmitter = /** @class */ (function () {
  52051. /**
  52052. * Creates a new instance of @see SphereParticleEmitter
  52053. * @param radius the radius of the emission sphere (1 by default)
  52054. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52055. */
  52056. function SphereParticleEmitter(
  52057. /**
  52058. * The radius of the emission sphere.
  52059. */
  52060. radius,
  52061. /**
  52062. * How much to randomize the particle direction [0-1].
  52063. */
  52064. directionRandomizer) {
  52065. if (radius === void 0) { radius = 1; }
  52066. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52067. this.radius = radius;
  52068. this.directionRandomizer = directionRandomizer;
  52069. }
  52070. /**
  52071. * Called by the particle System when the direction is computed for the created particle.
  52072. * @param emitPower is the power of the particle (speed)
  52073. * @param worldMatrix is the world matrix of the particle system
  52074. * @param directionToUpdate is the direction vector to update with the result
  52075. * @param particle is the particle we are computed the direction for
  52076. */
  52077. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52078. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52079. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52080. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52081. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52082. direction.x += randX;
  52083. direction.y += randY;
  52084. direction.z += randZ;
  52085. direction.normalize();
  52086. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52087. };
  52088. /**
  52089. * Called by the particle System when the position is computed for the created particle.
  52090. * @param worldMatrix is the world matrix of the particle system
  52091. * @param positionToUpdate is the position vector to update with the result
  52092. * @param particle is the particle we are computed the position for
  52093. */
  52094. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52095. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52096. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52097. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52098. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52099. var randY = randRadius * Math.cos(theta);
  52100. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52101. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52102. };
  52103. /**
  52104. * Clones the current emitter and returns a copy of it
  52105. * @returns the new emitter
  52106. */
  52107. SphereParticleEmitter.prototype.clone = function () {
  52108. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52109. BABYLON.Tools.DeepCopy(this, newOne);
  52110. return newOne;
  52111. };
  52112. /**
  52113. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52114. * @param effect defines the update shader
  52115. */
  52116. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52117. effect.setFloat("radius", this.radius);
  52118. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52119. };
  52120. /**
  52121. * Returns a string to use to update the GPU particles update shader
  52122. * @returns a string containng the defines string
  52123. */
  52124. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52125. return "#define SPHEREEMITTER";
  52126. };
  52127. /**
  52128. * Returns the string "SphereParticleEmitter"
  52129. * @returns a string containing the class name
  52130. */
  52131. SphereParticleEmitter.prototype.getClassName = function () {
  52132. return "SphereParticleEmitter";
  52133. };
  52134. /**
  52135. * Serializes the particle system to a JSON object.
  52136. * @returns the JSON object
  52137. */
  52138. SphereParticleEmitter.prototype.serialize = function () {
  52139. var serializationObject = {};
  52140. serializationObject.type = this.getClassName();
  52141. serializationObject.radius = this.radius;
  52142. serializationObject.directionRandomizer = this.directionRandomizer;
  52143. return serializationObject;
  52144. };
  52145. /**
  52146. * Parse properties from a JSON object
  52147. * @param serializationObject defines the JSON object
  52148. */
  52149. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52150. this.radius = serializationObject.radius;
  52151. this.directionRandomizer = serializationObject.directionRandomizer;
  52152. };
  52153. return SphereParticleEmitter;
  52154. }());
  52155. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52156. /**
  52157. * Particle emitter emitting particles from the inside of a sphere.
  52158. * It emits the particles randomly between two vectors.
  52159. */
  52160. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52161. __extends(SphereDirectedParticleEmitter, _super);
  52162. /**
  52163. * Creates a new instance of @see SphereDirectedParticleEmitter
  52164. * @param radius the radius of the emission sphere (1 by default)
  52165. * @param direction1 the min limit of the emission direction (up vector by default)
  52166. * @param direction2 the max limit of the emission direction (up vector by default)
  52167. */
  52168. function SphereDirectedParticleEmitter(radius,
  52169. /**
  52170. * The min limit of the emission direction.
  52171. */
  52172. direction1,
  52173. /**
  52174. * The max limit of the emission direction.
  52175. */
  52176. direction2) {
  52177. if (radius === void 0) { radius = 1; }
  52178. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52179. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52180. var _this = _super.call(this, radius) || this;
  52181. _this.direction1 = direction1;
  52182. _this.direction2 = direction2;
  52183. return _this;
  52184. }
  52185. /**
  52186. * Called by the particle System when the direction is computed for the created particle.
  52187. * @param emitPower is the power of the particle (speed)
  52188. * @param worldMatrix is the world matrix of the particle system
  52189. * @param directionToUpdate is the direction vector to update with the result
  52190. * @param particle is the particle we are computed the direction for
  52191. */
  52192. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52193. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52194. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52195. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52196. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52197. };
  52198. /**
  52199. * Clones the current emitter and returns a copy of it
  52200. * @returns the new emitter
  52201. */
  52202. SphereDirectedParticleEmitter.prototype.clone = function () {
  52203. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52204. BABYLON.Tools.DeepCopy(this, newOne);
  52205. return newOne;
  52206. };
  52207. /**
  52208. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52209. * @param effect defines the update shader
  52210. */
  52211. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52212. effect.setFloat("radius", this.radius);
  52213. effect.setVector3("direction1", this.direction1);
  52214. effect.setVector3("direction2", this.direction2);
  52215. };
  52216. /**
  52217. * Returns a string to use to update the GPU particles update shader
  52218. * @returns a string containng the defines string
  52219. */
  52220. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52221. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52222. };
  52223. /**
  52224. * Returns the string "SphereDirectedParticleEmitter"
  52225. * @returns a string containing the class name
  52226. */
  52227. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52228. return "SphereDirectedParticleEmitter";
  52229. };
  52230. /**
  52231. * Serializes the particle system to a JSON object.
  52232. * @returns the JSON object
  52233. */
  52234. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52235. var serializationObject = _super.prototype.serialize.call(this);
  52236. ;
  52237. serializationObject.direction1 = this.direction1.asArray();
  52238. ;
  52239. serializationObject.direction2 = this.direction2.asArray();
  52240. ;
  52241. return serializationObject;
  52242. };
  52243. /**
  52244. * Parse properties from a JSON object
  52245. * @param serializationObject defines the JSON object
  52246. */
  52247. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52248. _super.prototype.parse.call(this, serializationObject);
  52249. this.direction1.copyFrom(serializationObject.direction1);
  52250. this.direction2.copyFrom(serializationObject.direction2);
  52251. };
  52252. return SphereDirectedParticleEmitter;
  52253. }(SphereParticleEmitter));
  52254. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52255. })(BABYLON || (BABYLON = {}));
  52256. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52257. var BABYLON;
  52258. (function (BABYLON) {
  52259. /**
  52260. * Represents one particle of a solid particle system.
  52261. * @see SolidParticleSystem
  52262. */
  52263. var SolidParticle = /** @class */ (function () {
  52264. /**
  52265. * Creates a Solid Particle object.
  52266. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52267. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52268. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52269. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52270. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52271. * @param shapeId (integer) is the model shape identifier in the SPS.
  52272. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52273. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52274. */
  52275. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52276. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52277. /**
  52278. * particle global index
  52279. */
  52280. this.idx = 0;
  52281. /**
  52282. * The color of the particle
  52283. */
  52284. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52285. /**
  52286. * The world space position of the particle.
  52287. */
  52288. this.position = BABYLON.Vector3.Zero();
  52289. /**
  52290. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52291. */
  52292. this.rotation = BABYLON.Vector3.Zero();
  52293. /**
  52294. * The scaling of the particle.
  52295. */
  52296. this.scaling = BABYLON.Vector3.One();
  52297. /**
  52298. * The uvs of the particle.
  52299. */
  52300. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52301. /**
  52302. * The current speed of the particle.
  52303. */
  52304. this.velocity = BABYLON.Vector3.Zero();
  52305. /**
  52306. * The pivot point in the particle local space.
  52307. */
  52308. this.pivot = BABYLON.Vector3.Zero();
  52309. /**
  52310. * Must the particle be translated from its pivot point in its local space ?
  52311. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52312. * Default : false
  52313. */
  52314. this.translateFromPivot = false;
  52315. /**
  52316. * Is the particle active or not ?
  52317. */
  52318. this.alive = true;
  52319. /**
  52320. * Is the particle visible or not ?
  52321. */
  52322. this.isVisible = true;
  52323. /**
  52324. * Index of this particle in the global "positions" array (Internal use)
  52325. */
  52326. this._pos = 0;
  52327. /**
  52328. * Index of this particle in the global "indices" array (Internal use)
  52329. */
  52330. this._ind = 0;
  52331. /**
  52332. * ModelShape id of this particle
  52333. */
  52334. this.shapeId = 0;
  52335. /**
  52336. * Index of the particle in its shape id (Internal use)
  52337. */
  52338. this.idxInShape = 0;
  52339. /**
  52340. * Still set as invisible in order to skip useless computations (Internal use)
  52341. */
  52342. this._stillInvisible = false;
  52343. /**
  52344. * Last computed particle rotation matrix
  52345. */
  52346. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52347. /**
  52348. * Parent particle Id, if any.
  52349. * Default null.
  52350. */
  52351. this.parentId = null;
  52352. /**
  52353. * Internal global position in the SPS.
  52354. */
  52355. this._globalPosition = BABYLON.Vector3.Zero();
  52356. this.idx = particleIndex;
  52357. this._pos = positionIndex;
  52358. this._ind = indiceIndex;
  52359. this._model = model;
  52360. this.shapeId = shapeId;
  52361. this.idxInShape = idxInShape;
  52362. this._sps = sps;
  52363. if (modelBoundingInfo) {
  52364. this._modelBoundingInfo = modelBoundingInfo;
  52365. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52366. }
  52367. }
  52368. Object.defineProperty(SolidParticle.prototype, "scale", {
  52369. /**
  52370. * Legacy support, changed scale to scaling
  52371. */
  52372. get: function () {
  52373. return this.scaling;
  52374. },
  52375. /**
  52376. * Legacy support, changed scale to scaling
  52377. */
  52378. set: function (scale) {
  52379. this.scaling = scale;
  52380. },
  52381. enumerable: true,
  52382. configurable: true
  52383. });
  52384. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52385. /**
  52386. * Legacy support, changed quaternion to rotationQuaternion
  52387. */
  52388. get: function () {
  52389. return this.rotationQuaternion;
  52390. },
  52391. /**
  52392. * Legacy support, changed quaternion to rotationQuaternion
  52393. */
  52394. set: function (q) {
  52395. this.rotationQuaternion = q;
  52396. },
  52397. enumerable: true,
  52398. configurable: true
  52399. });
  52400. /**
  52401. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52402. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52403. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52404. * @returns true if it intersects
  52405. */
  52406. SolidParticle.prototype.intersectsMesh = function (target) {
  52407. if (!this._boundingInfo || !target._boundingInfo) {
  52408. return false;
  52409. }
  52410. if (this._sps._bSphereOnly) {
  52411. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52412. }
  52413. return this._boundingInfo.intersects(target._boundingInfo, false);
  52414. };
  52415. return SolidParticle;
  52416. }());
  52417. BABYLON.SolidParticle = SolidParticle;
  52418. /**
  52419. * Represents the shape of the model used by one particle of a solid particle system.
  52420. * SPS internal tool, don't use it manually.
  52421. * @see SolidParticleSystem
  52422. */
  52423. var ModelShape = /** @class */ (function () {
  52424. /**
  52425. * 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.
  52426. * SPS internal tool, don't use it manually.
  52427. * @ignore
  52428. */
  52429. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52430. /**
  52431. * length of the shape in the model indices array (internal use)
  52432. */
  52433. this._indicesLength = 0;
  52434. this.shapeID = id;
  52435. this._shape = shape;
  52436. this._indicesLength = indicesLength;
  52437. this._shapeUV = shapeUV;
  52438. this._positionFunction = posFunction;
  52439. this._vertexFunction = vtxFunction;
  52440. }
  52441. return ModelShape;
  52442. }());
  52443. BABYLON.ModelShape = ModelShape;
  52444. /**
  52445. * Represents a Depth Sorted Particle in the solid particle system.
  52446. * @see SolidParticleSystem
  52447. */
  52448. var DepthSortedParticle = /** @class */ (function () {
  52449. function DepthSortedParticle() {
  52450. /**
  52451. * Index of the particle in the "indices" array
  52452. */
  52453. this.ind = 0;
  52454. /**
  52455. * Length of the particle shape in the "indices" array
  52456. */
  52457. this.indicesLength = 0;
  52458. /**
  52459. * Squared distance from the particle to the camera
  52460. */
  52461. this.sqDistance = 0.0;
  52462. }
  52463. return DepthSortedParticle;
  52464. }());
  52465. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52466. })(BABYLON || (BABYLON = {}));
  52467. //# sourceMappingURL=babylon.solidParticle.js.map
  52468. var BABYLON;
  52469. (function (BABYLON) {
  52470. /**
  52471. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52472. *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.
  52473. * The SPS is also a particle system. It provides some methods to manage the particles.
  52474. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52475. *
  52476. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52477. */
  52478. var SolidParticleSystem = /** @class */ (function () {
  52479. /**
  52480. * Creates a SPS (Solid Particle System) object.
  52481. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52482. * @param scene (Scene) is the scene in which the SPS is added.
  52483. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52484. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52485. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52486. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52487. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52488. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52489. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52490. */
  52491. function SolidParticleSystem(name, scene, options) {
  52492. /**
  52493. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52494. * Example : var p = SPS.particles[i];
  52495. */
  52496. this.particles = new Array();
  52497. /**
  52498. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52499. */
  52500. this.nbParticles = 0;
  52501. /**
  52502. * If the particles must ever face the camera (default false). Useful for planar particles.
  52503. */
  52504. this.billboard = false;
  52505. /**
  52506. * Recompute normals when adding a shape
  52507. */
  52508. this.recomputeNormals = true;
  52509. /**
  52510. * This a counter ofr your own usage. It's not set by any SPS functions.
  52511. */
  52512. this.counter = 0;
  52513. /**
  52514. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52515. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52516. */
  52517. this.vars = {};
  52518. /**
  52519. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52520. */
  52521. this._bSphereOnly = false;
  52522. /**
  52523. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52524. */
  52525. this._bSphereRadiusFactor = 1.0;
  52526. this._positions = new Array();
  52527. this._indices = new Array();
  52528. this._normals = new Array();
  52529. this._colors = new Array();
  52530. this._uvs = new Array();
  52531. this._index = 0; // indices index
  52532. this._updatable = true;
  52533. this._pickable = false;
  52534. this._isVisibilityBoxLocked = false;
  52535. this._alwaysVisible = false;
  52536. this._depthSort = false;
  52537. this._shapeCounter = 0;
  52538. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52539. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52540. this._computeParticleColor = true;
  52541. this._computeParticleTexture = true;
  52542. this._computeParticleRotation = true;
  52543. this._computeParticleVertex = false;
  52544. this._computeBoundingBox = false;
  52545. this._depthSortParticles = true;
  52546. this._cam_axisZ = BABYLON.Vector3.Zero();
  52547. this._cam_axisY = BABYLON.Vector3.Zero();
  52548. this._cam_axisX = BABYLON.Vector3.Zero();
  52549. this._axisZ = BABYLON.Axis.Z;
  52550. this._camDir = BABYLON.Vector3.Zero();
  52551. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52552. this._rotMatrix = new BABYLON.Matrix();
  52553. this._invertMatrix = new BABYLON.Matrix();
  52554. this._rotated = BABYLON.Vector3.Zero();
  52555. this._quaternion = new BABYLON.Quaternion();
  52556. this._vertex = BABYLON.Vector3.Zero();
  52557. this._normal = BABYLON.Vector3.Zero();
  52558. this._yaw = 0.0;
  52559. this._pitch = 0.0;
  52560. this._roll = 0.0;
  52561. this._halfroll = 0.0;
  52562. this._halfpitch = 0.0;
  52563. this._halfyaw = 0.0;
  52564. this._sinRoll = 0.0;
  52565. this._cosRoll = 0.0;
  52566. this._sinPitch = 0.0;
  52567. this._cosPitch = 0.0;
  52568. this._sinYaw = 0.0;
  52569. this._cosYaw = 0.0;
  52570. this._mustUnrotateFixedNormals = false;
  52571. this._minimum = BABYLON.Vector3.Zero();
  52572. this._maximum = BABYLON.Vector3.Zero();
  52573. this._minBbox = BABYLON.Vector3.Zero();
  52574. this._maxBbox = BABYLON.Vector3.Zero();
  52575. this._particlesIntersect = false;
  52576. this._depthSortFunction = function (p1, p2) {
  52577. return (p2.sqDistance - p1.sqDistance);
  52578. };
  52579. this._needs32Bits = false;
  52580. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52581. this._scaledPivot = BABYLON.Vector3.Zero();
  52582. this._particleHasParent = false;
  52583. this.name = name;
  52584. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52585. this._camera = scene.activeCamera;
  52586. this._pickable = options ? options.isPickable : false;
  52587. this._depthSort = options ? options.enableDepthSort : false;
  52588. this._particlesIntersect = options ? options.particleIntersection : false;
  52589. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52590. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52591. if (options && options.updatable) {
  52592. this._updatable = options.updatable;
  52593. }
  52594. else {
  52595. this._updatable = true;
  52596. }
  52597. if (this._pickable) {
  52598. this.pickedParticles = [];
  52599. }
  52600. if (this._depthSort) {
  52601. this.depthSortedParticles = [];
  52602. }
  52603. }
  52604. /**
  52605. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52606. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52607. * @returns the created mesh
  52608. */
  52609. SolidParticleSystem.prototype.buildMesh = function () {
  52610. if (this.nbParticles === 0) {
  52611. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52612. this.addShape(triangle, 1);
  52613. triangle.dispose();
  52614. }
  52615. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52616. this._positions32 = new Float32Array(this._positions);
  52617. this._uvs32 = new Float32Array(this._uvs);
  52618. this._colors32 = new Float32Array(this._colors);
  52619. if (this.recomputeNormals) {
  52620. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52621. }
  52622. this._normals32 = new Float32Array(this._normals);
  52623. this._fixedNormal32 = new Float32Array(this._normals);
  52624. if (this._mustUnrotateFixedNormals) {
  52625. this._unrotateFixedNormals();
  52626. }
  52627. var vertexData = new BABYLON.VertexData();
  52628. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52629. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52630. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52631. if (this._uvs32) {
  52632. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52633. ;
  52634. }
  52635. if (this._colors32) {
  52636. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52637. }
  52638. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52639. vertexData.applyToMesh(mesh, this._updatable);
  52640. this.mesh = mesh;
  52641. this.mesh.isPickable = this._pickable;
  52642. // free memory
  52643. if (!this._depthSort) {
  52644. this._indices = null;
  52645. }
  52646. this._positions = null;
  52647. this._normals = null;
  52648. this._uvs = null;
  52649. this._colors = null;
  52650. if (!this._updatable) {
  52651. this.particles.length = 0;
  52652. }
  52653. return mesh;
  52654. };
  52655. /**
  52656. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52657. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52658. * Thus the particles generated from `digest()` have their property `position` set yet.
  52659. * @param mesh ( Mesh ) is the mesh to be digested
  52660. * @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
  52661. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52662. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52663. * @returns the current SPS
  52664. */
  52665. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52666. var size = (options && options.facetNb) || 1;
  52667. var number = (options && options.number) || 0;
  52668. var delta = (options && options.delta) || 0;
  52669. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52670. var meshInd = mesh.getIndices();
  52671. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52672. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52673. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52674. var f = 0; // facet counter
  52675. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52676. // compute size from number
  52677. if (number) {
  52678. number = (number > totalFacets) ? totalFacets : number;
  52679. size = Math.round(totalFacets / number);
  52680. delta = 0;
  52681. }
  52682. else {
  52683. size = (size > totalFacets) ? totalFacets : size;
  52684. }
  52685. var facetPos = []; // submesh positions
  52686. var facetInd = []; // submesh indices
  52687. var facetUV = []; // submesh UV
  52688. var facetCol = []; // submesh colors
  52689. var barycenter = BABYLON.Vector3.Zero();
  52690. var sizeO = size;
  52691. while (f < totalFacets) {
  52692. size = sizeO + Math.floor((1 + delta) * Math.random());
  52693. if (f > totalFacets - size) {
  52694. size = totalFacets - f;
  52695. }
  52696. // reset temp arrays
  52697. facetPos.length = 0;
  52698. facetInd.length = 0;
  52699. facetUV.length = 0;
  52700. facetCol.length = 0;
  52701. // iterate over "size" facets
  52702. var fi = 0;
  52703. for (var j = f * 3; j < (f + size) * 3; j++) {
  52704. facetInd.push(fi);
  52705. var i = meshInd[j];
  52706. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52707. if (meshUV) {
  52708. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52709. }
  52710. if (meshCol) {
  52711. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52712. }
  52713. fi++;
  52714. }
  52715. // create a model shape for each single particle
  52716. var idx = this.nbParticles;
  52717. var shape = this._posToShape(facetPos);
  52718. var shapeUV = this._uvsToShapeUV(facetUV);
  52719. // compute the barycenter of the shape
  52720. var v;
  52721. for (v = 0; v < shape.length; v++) {
  52722. barycenter.addInPlace(shape[v]);
  52723. }
  52724. barycenter.scaleInPlace(1 / shape.length);
  52725. // shift the shape from its barycenter to the origin
  52726. for (v = 0; v < shape.length; v++) {
  52727. shape[v].subtractInPlace(barycenter);
  52728. }
  52729. var bInfo;
  52730. if (this._particlesIntersect) {
  52731. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52732. }
  52733. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52734. // add the particle in the SPS
  52735. var currentPos = this._positions.length;
  52736. var currentInd = this._indices.length;
  52737. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52738. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52739. // initialize the particle position
  52740. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52741. this._index += shape.length;
  52742. idx++;
  52743. this.nbParticles++;
  52744. this._shapeCounter++;
  52745. f += size;
  52746. }
  52747. return this;
  52748. };
  52749. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52750. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52751. var index = 0;
  52752. var idx = 0;
  52753. for (var p = 0; p < this.particles.length; p++) {
  52754. this._particle = this.particles[p];
  52755. this._shape = this._particle._model._shape;
  52756. if (this._particle.rotationQuaternion) {
  52757. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52758. }
  52759. else {
  52760. this._yaw = this._particle.rotation.y;
  52761. this._pitch = this._particle.rotation.x;
  52762. this._roll = this._particle.rotation.z;
  52763. this._quaternionRotationYPR();
  52764. }
  52765. this._quaternionToRotationMatrix();
  52766. this._rotMatrix.invertToRef(this._invertMatrix);
  52767. for (var pt = 0; pt < this._shape.length; pt++) {
  52768. idx = index + pt * 3;
  52769. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52770. this._fixedNormal32[idx] = this._normal.x;
  52771. this._fixedNormal32[idx + 1] = this._normal.y;
  52772. this._fixedNormal32[idx + 2] = this._normal.z;
  52773. }
  52774. index = idx + 3;
  52775. }
  52776. };
  52777. //reset copy
  52778. SolidParticleSystem.prototype._resetCopy = function () {
  52779. this._copy.position.x = 0;
  52780. this._copy.position.y = 0;
  52781. this._copy.position.z = 0;
  52782. this._copy.rotation.x = 0;
  52783. this._copy.rotation.y = 0;
  52784. this._copy.rotation.z = 0;
  52785. this._copy.rotationQuaternion = null;
  52786. this._copy.scaling.x = 1.0;
  52787. this._copy.scaling.y = 1.0;
  52788. this._copy.scaling.z = 1.0;
  52789. this._copy.uvs.x = 0;
  52790. this._copy.uvs.y = 0;
  52791. this._copy.uvs.z = 1.0;
  52792. this._copy.uvs.w = 1.0;
  52793. this._copy.color = null;
  52794. this._copy.translateFromPivot = false;
  52795. };
  52796. // _meshBuilder : inserts the shape model in the global SPS mesh
  52797. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52798. var i;
  52799. var u = 0;
  52800. var c = 0;
  52801. var n = 0;
  52802. this._resetCopy();
  52803. if (options && options.positionFunction) {
  52804. options.positionFunction(this._copy, idx, idxInShape);
  52805. this._mustUnrotateFixedNormals = true;
  52806. }
  52807. if (this._copy.rotationQuaternion) {
  52808. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52809. }
  52810. else {
  52811. this._yaw = this._copy.rotation.y;
  52812. this._pitch = this._copy.rotation.x;
  52813. this._roll = this._copy.rotation.z;
  52814. this._quaternionRotationYPR();
  52815. }
  52816. this._quaternionToRotationMatrix();
  52817. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52818. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52819. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52820. if (this._copy.translateFromPivot) {
  52821. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52822. }
  52823. else {
  52824. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52825. }
  52826. for (i = 0; i < shape.length; i++) {
  52827. this._vertex.x = shape[i].x;
  52828. this._vertex.y = shape[i].y;
  52829. this._vertex.z = shape[i].z;
  52830. if (options && options.vertexFunction) {
  52831. options.vertexFunction(this._copy, this._vertex, i);
  52832. }
  52833. this._vertex.x *= this._copy.scaling.x;
  52834. this._vertex.y *= this._copy.scaling.y;
  52835. this._vertex.z *= this._copy.scaling.z;
  52836. this._vertex.x -= this._scaledPivot.x;
  52837. this._vertex.y -= this._scaledPivot.y;
  52838. this._vertex.z -= this._scaledPivot.z;
  52839. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52840. this._rotated.addInPlace(this._pivotBackTranslation);
  52841. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52842. if (meshUV) {
  52843. 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);
  52844. u += 2;
  52845. }
  52846. if (this._copy.color) {
  52847. this._color = this._copy.color;
  52848. }
  52849. else if (meshCol && meshCol[c] !== undefined) {
  52850. this._color.r = meshCol[c];
  52851. this._color.g = meshCol[c + 1];
  52852. this._color.b = meshCol[c + 2];
  52853. this._color.a = meshCol[c + 3];
  52854. }
  52855. else {
  52856. this._color.r = 1.0;
  52857. this._color.g = 1.0;
  52858. this._color.b = 1.0;
  52859. this._color.a = 1.0;
  52860. }
  52861. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52862. c += 4;
  52863. if (!this.recomputeNormals && meshNor) {
  52864. this._normal.x = meshNor[n];
  52865. this._normal.y = meshNor[n + 1];
  52866. this._normal.z = meshNor[n + 2];
  52867. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52868. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52869. n += 3;
  52870. }
  52871. }
  52872. for (i = 0; i < meshInd.length; i++) {
  52873. var current_ind = p + meshInd[i];
  52874. indices.push(current_ind);
  52875. if (current_ind > 65535) {
  52876. this._needs32Bits = true;
  52877. }
  52878. }
  52879. if (this._pickable) {
  52880. var nbfaces = meshInd.length / 3;
  52881. for (i = 0; i < nbfaces; i++) {
  52882. this.pickedParticles.push({ idx: idx, faceId: i });
  52883. }
  52884. }
  52885. if (this._depthSort) {
  52886. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52887. }
  52888. return this._copy;
  52889. };
  52890. // returns a shape array from positions array
  52891. SolidParticleSystem.prototype._posToShape = function (positions) {
  52892. var shape = [];
  52893. for (var i = 0; i < positions.length; i += 3) {
  52894. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52895. }
  52896. return shape;
  52897. };
  52898. // returns a shapeUV array from a Vector4 uvs
  52899. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52900. var shapeUV = [];
  52901. if (uvs) {
  52902. for (var i = 0; i < uvs.length; i++)
  52903. shapeUV.push(uvs[i]);
  52904. }
  52905. return shapeUV;
  52906. };
  52907. // adds a new particle object in the particles array
  52908. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52909. if (bInfo === void 0) { bInfo = null; }
  52910. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52911. this.particles.push(sp);
  52912. return sp;
  52913. };
  52914. /**
  52915. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52916. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52917. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52918. * @param nb (positive integer) the number of particles to be created from this model
  52919. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52920. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52921. * @returns the number of shapes in the system
  52922. */
  52923. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52924. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52925. var meshInd = mesh.getIndices();
  52926. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52927. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52928. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52929. var bbInfo;
  52930. if (this._particlesIntersect) {
  52931. bbInfo = mesh.getBoundingInfo();
  52932. }
  52933. var shape = this._posToShape(meshPos);
  52934. var shapeUV = this._uvsToShapeUV(meshUV);
  52935. var posfunc = options ? options.positionFunction : null;
  52936. var vtxfunc = options ? options.vertexFunction : null;
  52937. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52938. // particles
  52939. var sp;
  52940. var currentCopy;
  52941. var idx = this.nbParticles;
  52942. for (var i = 0; i < nb; i++) {
  52943. var currentPos = this._positions.length;
  52944. var currentInd = this._indices.length;
  52945. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52946. if (this._updatable) {
  52947. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52948. sp.position.copyFrom(currentCopy.position);
  52949. sp.rotation.copyFrom(currentCopy.rotation);
  52950. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52951. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52952. }
  52953. if (currentCopy.color && sp.color) {
  52954. sp.color.copyFrom(currentCopy.color);
  52955. }
  52956. sp.scaling.copyFrom(currentCopy.scaling);
  52957. sp.uvs.copyFrom(currentCopy.uvs);
  52958. }
  52959. this._index += shape.length;
  52960. idx++;
  52961. }
  52962. this.nbParticles += nb;
  52963. this._shapeCounter++;
  52964. return this._shapeCounter - 1;
  52965. };
  52966. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52967. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52968. this._resetCopy();
  52969. if (particle._model._positionFunction) {
  52970. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52971. }
  52972. if (this._copy.rotationQuaternion) {
  52973. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52974. }
  52975. else {
  52976. this._yaw = this._copy.rotation.y;
  52977. this._pitch = this._copy.rotation.x;
  52978. this._roll = this._copy.rotation.z;
  52979. this._quaternionRotationYPR();
  52980. }
  52981. this._quaternionToRotationMatrix();
  52982. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52983. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52984. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52985. if (this._copy.translateFromPivot) {
  52986. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52987. }
  52988. else {
  52989. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52990. }
  52991. this._shape = particle._model._shape;
  52992. for (var pt = 0; pt < this._shape.length; pt++) {
  52993. this._vertex.x = this._shape[pt].x;
  52994. this._vertex.y = this._shape[pt].y;
  52995. this._vertex.z = this._shape[pt].z;
  52996. if (particle._model._vertexFunction) {
  52997. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52998. }
  52999. this._vertex.x *= this._copy.scaling.x;
  53000. this._vertex.y *= this._copy.scaling.y;
  53001. this._vertex.z *= this._copy.scaling.z;
  53002. this._vertex.x -= this._scaledPivot.x;
  53003. this._vertex.y -= this._scaledPivot.y;
  53004. this._vertex.z -= this._scaledPivot.z;
  53005. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53006. this._rotated.addInPlace(this._pivotBackTranslation);
  53007. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53008. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53009. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53010. }
  53011. particle.position.x = 0.0;
  53012. particle.position.y = 0.0;
  53013. particle.position.z = 0.0;
  53014. particle.rotation.x = 0.0;
  53015. particle.rotation.y = 0.0;
  53016. particle.rotation.z = 0.0;
  53017. particle.rotationQuaternion = null;
  53018. particle.scaling.x = 1.0;
  53019. particle.scaling.y = 1.0;
  53020. particle.scaling.z = 1.0;
  53021. particle.uvs.x = 0.0;
  53022. particle.uvs.y = 0.0;
  53023. particle.uvs.z = 1.0;
  53024. particle.uvs.w = 1.0;
  53025. particle.pivot.x = 0.0;
  53026. particle.pivot.y = 0.0;
  53027. particle.pivot.z = 0.0;
  53028. particle.translateFromPivot = false;
  53029. particle.parentId = null;
  53030. };
  53031. /**
  53032. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53033. * @returns the SPS.
  53034. */
  53035. SolidParticleSystem.prototype.rebuildMesh = function () {
  53036. for (var p = 0; p < this.particles.length; p++) {
  53037. this._rebuildParticle(this.particles[p]);
  53038. }
  53039. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53040. return this;
  53041. };
  53042. /**
  53043. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53044. * This method calls `updateParticle()` for each particle of the SPS.
  53045. * For an animated SPS, it is usually called within the render loop.
  53046. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53047. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53048. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53049. * @returns the SPS.
  53050. */
  53051. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53052. if (start === void 0) { start = 0; }
  53053. if (end === void 0) { end = this.nbParticles - 1; }
  53054. if (update === void 0) { update = true; }
  53055. if (!this._updatable) {
  53056. return this;
  53057. }
  53058. // custom beforeUpdate
  53059. this.beforeUpdateParticles(start, end, update);
  53060. this._cam_axisX.x = 1.0;
  53061. this._cam_axisX.y = 0.0;
  53062. this._cam_axisX.z = 0.0;
  53063. this._cam_axisY.x = 0.0;
  53064. this._cam_axisY.y = 1.0;
  53065. this._cam_axisY.z = 0.0;
  53066. this._cam_axisZ.x = 0.0;
  53067. this._cam_axisZ.y = 0.0;
  53068. this._cam_axisZ.z = 1.0;
  53069. // cases when the World Matrix is to be computed first
  53070. if (this.billboard || this._depthSort) {
  53071. this.mesh.computeWorldMatrix(true);
  53072. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53073. }
  53074. // if the particles will always face the camera
  53075. if (this.billboard) {
  53076. // compute the camera position and un-rotate it by the current mesh rotation
  53077. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53078. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53079. this._cam_axisZ.normalize();
  53080. // same for camera up vector extracted from the cam view matrix
  53081. var view = this._camera.getViewMatrix(true);
  53082. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53083. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53084. this._cam_axisY.normalize();
  53085. this._cam_axisX.normalize();
  53086. }
  53087. // if depthSort, compute the camera global position in the mesh local system
  53088. if (this._depthSort) {
  53089. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53090. }
  53091. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53092. var idx = 0; // current position index in the global array positions32
  53093. var index = 0; // position start index in the global array positions32 of the current particle
  53094. var colidx = 0; // current color index in the global array colors32
  53095. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53096. var uvidx = 0; // current uv index in the global array uvs32
  53097. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53098. var pt = 0; // current index in the particle model shape
  53099. if (this.mesh.isFacetDataEnabled) {
  53100. this._computeBoundingBox = true;
  53101. }
  53102. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53103. if (this._computeBoundingBox) {
  53104. if (start == 0 && end == this.nbParticles - 1) {
  53105. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53106. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53107. }
  53108. else {
  53109. if (this.mesh._boundingInfo) {
  53110. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53111. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53112. }
  53113. }
  53114. }
  53115. // particle loop
  53116. index = this.particles[start]._pos;
  53117. var vpos = (index / 3) | 0;
  53118. colorIndex = vpos * 4;
  53119. uvIndex = vpos * 2;
  53120. for (var p = start; p <= end; p++) {
  53121. this._particle = this.particles[p];
  53122. this._shape = this._particle._model._shape;
  53123. this._shapeUV = this._particle._model._shapeUV;
  53124. // call to custom user function to update the particle properties
  53125. this.updateParticle(this._particle);
  53126. // camera-particle distance for depth sorting
  53127. if (this._depthSort && this._depthSortParticles) {
  53128. var dsp = this.depthSortedParticles[p];
  53129. dsp.ind = this._particle._ind;
  53130. dsp.indicesLength = this._particle._model._indicesLength;
  53131. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53132. }
  53133. // skip the computations for inactive or already invisible particles
  53134. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53135. // increment indexes for the next particle
  53136. pt = this._shape.length;
  53137. index += pt * 3;
  53138. colorIndex += pt * 4;
  53139. uvIndex += pt * 2;
  53140. continue;
  53141. }
  53142. if (this._particle.isVisible) {
  53143. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53144. this._particleHasParent = (this._particle.parentId !== null);
  53145. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53146. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53147. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53148. // particle rotation matrix
  53149. if (this.billboard) {
  53150. this._particle.rotation.x = 0.0;
  53151. this._particle.rotation.y = 0.0;
  53152. }
  53153. if (this._computeParticleRotation || this.billboard) {
  53154. if (this._particle.rotationQuaternion) {
  53155. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53156. }
  53157. else {
  53158. this._yaw = this._particle.rotation.y;
  53159. this._pitch = this._particle.rotation.x;
  53160. this._roll = this._particle.rotation.z;
  53161. this._quaternionRotationYPR();
  53162. }
  53163. this._quaternionToRotationMatrix();
  53164. }
  53165. if (this._particleHasParent) {
  53166. this._parent = this.particles[this._particle.parentId];
  53167. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  53168. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  53169. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  53170. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53171. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53172. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53173. if (this._computeParticleRotation || this.billboard) {
  53174. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  53175. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  53176. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  53177. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  53178. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  53179. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  53180. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  53181. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  53182. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  53183. }
  53184. }
  53185. else {
  53186. this._particle._globalPosition.x = this._particle.position.x;
  53187. this._particle._globalPosition.y = this._particle.position.y;
  53188. this._particle._globalPosition.z = this._particle.position.z;
  53189. if (this._computeParticleRotation || this.billboard) {
  53190. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53191. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53192. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53193. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53194. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53195. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53196. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53197. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53198. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53199. }
  53200. }
  53201. if (this._particle.translateFromPivot) {
  53202. this._pivotBackTranslation.x = 0.0;
  53203. this._pivotBackTranslation.y = 0.0;
  53204. this._pivotBackTranslation.z = 0.0;
  53205. }
  53206. else {
  53207. this._pivotBackTranslation.x = this._scaledPivot.x;
  53208. this._pivotBackTranslation.y = this._scaledPivot.y;
  53209. this._pivotBackTranslation.z = this._scaledPivot.z;
  53210. }
  53211. // particle vertex loop
  53212. for (pt = 0; pt < this._shape.length; pt++) {
  53213. idx = index + pt * 3;
  53214. colidx = colorIndex + pt * 4;
  53215. uvidx = uvIndex + pt * 2;
  53216. this._vertex.x = this._shape[pt].x;
  53217. this._vertex.y = this._shape[pt].y;
  53218. this._vertex.z = this._shape[pt].z;
  53219. if (this._computeParticleVertex) {
  53220. this.updateParticleVertex(this._particle, this._vertex, pt);
  53221. }
  53222. // positions
  53223. this._vertex.x *= this._particle.scaling.x;
  53224. this._vertex.y *= this._particle.scaling.y;
  53225. this._vertex.z *= this._particle.scaling.z;
  53226. this._vertex.x -= this._scaledPivot.x;
  53227. this._vertex.y -= this._scaledPivot.y;
  53228. this._vertex.z -= this._scaledPivot.z;
  53229. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53230. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53231. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53232. this._rotated.x += this._pivotBackTranslation.x;
  53233. this._rotated.y += this._pivotBackTranslation.y;
  53234. this._rotated.z += this._pivotBackTranslation.z;
  53235. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53236. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  53237. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  53238. if (this._computeBoundingBox) {
  53239. if (this._positions32[idx] < this._minimum.x) {
  53240. this._minimum.x = this._positions32[idx];
  53241. }
  53242. if (this._positions32[idx] > this._maximum.x) {
  53243. this._maximum.x = this._positions32[idx];
  53244. }
  53245. if (this._positions32[idx + 1] < this._minimum.y) {
  53246. this._minimum.y = this._positions32[idx + 1];
  53247. }
  53248. if (this._positions32[idx + 1] > this._maximum.y) {
  53249. this._maximum.y = this._positions32[idx + 1];
  53250. }
  53251. if (this._positions32[idx + 2] < this._minimum.z) {
  53252. this._minimum.z = this._positions32[idx + 2];
  53253. }
  53254. if (this._positions32[idx + 2] > this._maximum.z) {
  53255. this._maximum.z = this._positions32[idx + 2];
  53256. }
  53257. }
  53258. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53259. if (!this._computeParticleVertex) {
  53260. this._normal.x = this._fixedNormal32[idx];
  53261. this._normal.y = this._fixedNormal32[idx + 1];
  53262. this._normal.z = this._fixedNormal32[idx + 2];
  53263. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53264. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53265. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53266. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53267. 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;
  53268. 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;
  53269. }
  53270. if (this._computeParticleColor && this._particle.color) {
  53271. this._colors32[colidx] = this._particle.color.r;
  53272. this._colors32[colidx + 1] = this._particle.color.g;
  53273. this._colors32[colidx + 2] = this._particle.color.b;
  53274. this._colors32[colidx + 3] = this._particle.color.a;
  53275. }
  53276. if (this._computeParticleTexture) {
  53277. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53278. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53279. }
  53280. }
  53281. }
  53282. else {
  53283. this._particle._stillInvisible = true; // mark the particle as invisible
  53284. for (pt = 0; pt < this._shape.length; pt++) {
  53285. idx = index + pt * 3;
  53286. colidx = colorIndex + pt * 4;
  53287. uvidx = uvIndex + pt * 2;
  53288. this._positions32[idx] = 0.0;
  53289. this._positions32[idx + 1] = 0.0;
  53290. this._positions32[idx + 2] = 0.0;
  53291. this._normals32[idx] = 0.0;
  53292. this._normals32[idx + 1] = 0.0;
  53293. this._normals32[idx + 2] = 0.0;
  53294. if (this._computeParticleColor && this._particle.color) {
  53295. this._colors32[colidx] = this._particle.color.r;
  53296. this._colors32[colidx + 1] = this._particle.color.g;
  53297. this._colors32[colidx + 2] = this._particle.color.b;
  53298. this._colors32[colidx + 3] = this._particle.color.a;
  53299. }
  53300. if (this._computeParticleTexture) {
  53301. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53302. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53303. }
  53304. }
  53305. }
  53306. // if the particle intersections must be computed : update the bbInfo
  53307. if (this._particlesIntersect) {
  53308. var bInfo = this._particle._boundingInfo;
  53309. var bBox = bInfo.boundingBox;
  53310. var bSphere = bInfo.boundingSphere;
  53311. if (!this._bSphereOnly) {
  53312. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53313. for (var b = 0; b < bBox.vectors.length; b++) {
  53314. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53315. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53316. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53317. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53318. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53319. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53320. 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;
  53321. 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;
  53322. 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;
  53323. }
  53324. bBox._update(this.mesh._worldMatrix);
  53325. }
  53326. // place and scale the particle bouding sphere in the SPS local system, then update it
  53327. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53328. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53329. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53330. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53331. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53332. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53333. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53334. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53335. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53336. 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));
  53337. bSphere._update(this.mesh._worldMatrix);
  53338. }
  53339. // increment indexes for the next particle
  53340. index = idx + 3;
  53341. colorIndex = colidx + 4;
  53342. uvIndex = uvidx + 2;
  53343. }
  53344. // if the VBO must be updated
  53345. if (update) {
  53346. if (this._computeParticleColor) {
  53347. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53348. }
  53349. if (this._computeParticleTexture) {
  53350. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53351. }
  53352. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53353. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53354. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53355. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53356. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53357. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53358. for (var i = 0; i < this._normals32.length; i++) {
  53359. this._fixedNormal32[i] = this._normals32[i];
  53360. }
  53361. }
  53362. if (!this.mesh.areNormalsFrozen) {
  53363. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53364. }
  53365. }
  53366. if (this._depthSort && this._depthSortParticles) {
  53367. this.depthSortedParticles.sort(this._depthSortFunction);
  53368. var dspl = this.depthSortedParticles.length;
  53369. var sorted = 0;
  53370. var lind = 0;
  53371. var sind = 0;
  53372. var sid = 0;
  53373. for (sorted = 0; sorted < dspl; sorted++) {
  53374. lind = this.depthSortedParticles[sorted].indicesLength;
  53375. sind = this.depthSortedParticles[sorted].ind;
  53376. for (var i = 0; i < lind; i++) {
  53377. this._indices32[sid] = this._indices[sind + i];
  53378. sid++;
  53379. }
  53380. }
  53381. this.mesh.updateIndices(this._indices32);
  53382. }
  53383. }
  53384. if (this._computeBoundingBox) {
  53385. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53386. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53387. }
  53388. this.afterUpdateParticles(start, end, update);
  53389. return this;
  53390. };
  53391. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53392. this._halfroll = this._roll * 0.5;
  53393. this._halfpitch = this._pitch * 0.5;
  53394. this._halfyaw = this._yaw * 0.5;
  53395. this._sinRoll = Math.sin(this._halfroll);
  53396. this._cosRoll = Math.cos(this._halfroll);
  53397. this._sinPitch = Math.sin(this._halfpitch);
  53398. this._cosPitch = Math.cos(this._halfpitch);
  53399. this._sinYaw = Math.sin(this._halfyaw);
  53400. this._cosYaw = Math.cos(this._halfyaw);
  53401. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53402. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53403. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53404. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53405. };
  53406. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53407. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53408. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53409. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53410. this._rotMatrix.m[3] = 0;
  53411. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53412. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53413. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53414. this._rotMatrix.m[7] = 0;
  53415. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53416. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53417. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53418. this._rotMatrix.m[11] = 0;
  53419. this._rotMatrix.m[12] = 0;
  53420. this._rotMatrix.m[13] = 0;
  53421. this._rotMatrix.m[14] = 0;
  53422. this._rotMatrix.m[15] = 1.0;
  53423. };
  53424. /**
  53425. * Disposes the SPS.
  53426. */
  53427. SolidParticleSystem.prototype.dispose = function () {
  53428. this.mesh.dispose();
  53429. this.vars = null;
  53430. // drop references to internal big arrays for the GC
  53431. this._positions = null;
  53432. this._indices = null;
  53433. this._normals = null;
  53434. this._uvs = null;
  53435. this._colors = null;
  53436. this._indices32 = null;
  53437. this._positions32 = null;
  53438. this._normals32 = null;
  53439. this._fixedNormal32 = null;
  53440. this._uvs32 = null;
  53441. this._colors32 = null;
  53442. this.pickedParticles = null;
  53443. };
  53444. /**
  53445. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53446. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53447. * @returns the SPS.
  53448. */
  53449. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53450. if (!this._isVisibilityBoxLocked) {
  53451. this.mesh.refreshBoundingInfo();
  53452. }
  53453. return this;
  53454. };
  53455. /**
  53456. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53457. * @param size the size (float) of the visibility box
  53458. * note : this doesn't lock the SPS mesh bounding box.
  53459. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53460. */
  53461. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53462. var vis = size / 2;
  53463. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53464. };
  53465. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53466. /**
  53467. * Gets whether the SPS as always visible or not
  53468. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53469. */
  53470. get: function () {
  53471. return this._alwaysVisible;
  53472. },
  53473. /**
  53474. * Sets the SPS as always visible or not
  53475. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53476. */
  53477. set: function (val) {
  53478. this._alwaysVisible = val;
  53479. this.mesh.alwaysSelectAsActiveMesh = val;
  53480. },
  53481. enumerable: true,
  53482. configurable: true
  53483. });
  53484. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53485. /**
  53486. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53487. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53488. */
  53489. get: function () {
  53490. return this._isVisibilityBoxLocked;
  53491. },
  53492. /**
  53493. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53494. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53495. */
  53496. set: function (val) {
  53497. this._isVisibilityBoxLocked = val;
  53498. var boundingInfo = this.mesh.getBoundingInfo();
  53499. boundingInfo.isLocked = val;
  53500. },
  53501. enumerable: true,
  53502. configurable: true
  53503. });
  53504. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53505. /**
  53506. * Gets if `setParticles()` computes the particle rotations or not.
  53507. * Default value : true. The SPS is faster when it's set to false.
  53508. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53509. */
  53510. get: function () {
  53511. return this._computeParticleRotation;
  53512. },
  53513. /**
  53514. * Tells to `setParticles()` to compute the particle rotations or not.
  53515. * Default value : true. The SPS is faster when it's set to false.
  53516. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53517. */
  53518. set: function (val) {
  53519. this._computeParticleRotation = val;
  53520. },
  53521. enumerable: true,
  53522. configurable: true
  53523. });
  53524. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53525. /**
  53526. * Gets if `setParticles()` computes the particle colors or not.
  53527. * Default value : true. The SPS is faster when it's set to false.
  53528. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53529. */
  53530. get: function () {
  53531. return this._computeParticleColor;
  53532. },
  53533. /**
  53534. * Tells to `setParticles()` to compute the particle colors or not.
  53535. * Default value : true. The SPS is faster when it's set to false.
  53536. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53537. */
  53538. set: function (val) {
  53539. this._computeParticleColor = val;
  53540. },
  53541. enumerable: true,
  53542. configurable: true
  53543. });
  53544. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53545. /**
  53546. * Gets if `setParticles()` computes the particle textures or not.
  53547. * Default value : true. The SPS is faster when it's set to false.
  53548. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53549. */
  53550. get: function () {
  53551. return this._computeParticleTexture;
  53552. },
  53553. set: function (val) {
  53554. this._computeParticleTexture = val;
  53555. },
  53556. enumerable: true,
  53557. configurable: true
  53558. });
  53559. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53560. /**
  53561. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53562. * Default value : false. The SPS is faster when it's set to false.
  53563. * Note : the particle custom vertex positions aren't stored values.
  53564. */
  53565. get: function () {
  53566. return this._computeParticleVertex;
  53567. },
  53568. /**
  53569. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53570. * Default value : false. The SPS is faster when it's set to false.
  53571. * Note : the particle custom vertex positions aren't stored values.
  53572. */
  53573. set: function (val) {
  53574. this._computeParticleVertex = val;
  53575. },
  53576. enumerable: true,
  53577. configurable: true
  53578. });
  53579. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53580. /**
  53581. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53582. */
  53583. get: function () {
  53584. return this._computeBoundingBox;
  53585. },
  53586. /**
  53587. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53588. */
  53589. set: function (val) {
  53590. this._computeBoundingBox = val;
  53591. },
  53592. enumerable: true,
  53593. configurable: true
  53594. });
  53595. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53596. /**
  53597. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53598. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53599. * Default : `true`
  53600. */
  53601. get: function () {
  53602. return this._depthSortParticles;
  53603. },
  53604. /**
  53605. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53606. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53607. * Default : `true`
  53608. */
  53609. set: function (val) {
  53610. this._depthSortParticles = val;
  53611. },
  53612. enumerable: true,
  53613. configurable: true
  53614. });
  53615. // =======================================================================
  53616. // Particle behavior logic
  53617. // these following methods may be overwritten by the user to fit his needs
  53618. /**
  53619. * This function does nothing. It may be overwritten to set all the particle first values.
  53620. * The SPS doesn't call this function, you may have to call it by your own.
  53621. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53622. */
  53623. SolidParticleSystem.prototype.initParticles = function () {
  53624. };
  53625. /**
  53626. * This function does nothing. It may be overwritten to recycle a particle.
  53627. * The SPS doesn't call this function, you may have to call it by your own.
  53628. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53629. * @param particle The particle to recycle
  53630. * @returns the recycled particle
  53631. */
  53632. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53633. return particle;
  53634. };
  53635. /**
  53636. * Updates a particle : this function should be overwritten by the user.
  53637. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53638. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53639. * @example : just set a particle position or velocity and recycle conditions
  53640. * @param particle The particle to update
  53641. * @returns the updated particle
  53642. */
  53643. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53644. return particle;
  53645. };
  53646. /**
  53647. * Updates a vertex of a particle : it can be overwritten by the user.
  53648. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53649. * @param particle the current particle
  53650. * @param vertex the current index of the current particle
  53651. * @param pt the index of the current vertex in the particle shape
  53652. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53653. * @example : just set a vertex particle position
  53654. * @returns the updated vertex
  53655. */
  53656. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53657. return vertex;
  53658. };
  53659. /**
  53660. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53661. * This does nothing and may be overwritten by the user.
  53662. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53663. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53664. * @param update the boolean update value actually passed to setParticles()
  53665. */
  53666. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53667. };
  53668. /**
  53669. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53670. * This will be passed three parameters.
  53671. * This does nothing and may be overwritten by the user.
  53672. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53673. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53674. * @param update the boolean update value actually passed to setParticles()
  53675. */
  53676. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53677. };
  53678. return SolidParticleSystem;
  53679. }());
  53680. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53681. })(BABYLON || (BABYLON = {}));
  53682. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53683. var BABYLON;
  53684. (function (BABYLON) {
  53685. var ShaderMaterial = /** @class */ (function (_super) {
  53686. __extends(ShaderMaterial, _super);
  53687. function ShaderMaterial(name, scene, shaderPath, options) {
  53688. var _this = _super.call(this, name, scene) || this;
  53689. _this._textures = {};
  53690. _this._textureArrays = {};
  53691. _this._floats = {};
  53692. _this._ints = {};
  53693. _this._floatsArrays = {};
  53694. _this._colors3 = {};
  53695. _this._colors3Arrays = {};
  53696. _this._colors4 = {};
  53697. _this._vectors2 = {};
  53698. _this._vectors3 = {};
  53699. _this._vectors4 = {};
  53700. _this._matrices = {};
  53701. _this._matrices3x3 = {};
  53702. _this._matrices2x2 = {};
  53703. _this._vectors2Arrays = {};
  53704. _this._vectors3Arrays = {};
  53705. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53706. _this._shaderPath = shaderPath;
  53707. options.needAlphaBlending = options.needAlphaBlending || false;
  53708. options.needAlphaTesting = options.needAlphaTesting || false;
  53709. options.attributes = options.attributes || ["position", "normal", "uv"];
  53710. options.uniforms = options.uniforms || ["worldViewProjection"];
  53711. options.uniformBuffers = options.uniformBuffers || [];
  53712. options.samplers = options.samplers || [];
  53713. options.defines = options.defines || [];
  53714. _this._options = options;
  53715. return _this;
  53716. }
  53717. ShaderMaterial.prototype.getClassName = function () {
  53718. return "ShaderMaterial";
  53719. };
  53720. ShaderMaterial.prototype.needAlphaBlending = function () {
  53721. return this._options.needAlphaBlending;
  53722. };
  53723. ShaderMaterial.prototype.needAlphaTesting = function () {
  53724. return this._options.needAlphaTesting;
  53725. };
  53726. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53727. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53728. this._options.uniforms.push(uniformName);
  53729. }
  53730. };
  53731. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53732. if (this._options.samplers.indexOf(name) === -1) {
  53733. this._options.samplers.push(name);
  53734. }
  53735. this._textures[name] = texture;
  53736. return this;
  53737. };
  53738. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53739. if (this._options.samplers.indexOf(name) === -1) {
  53740. this._options.samplers.push(name);
  53741. }
  53742. this._checkUniform(name);
  53743. this._textureArrays[name] = textures;
  53744. return this;
  53745. };
  53746. ShaderMaterial.prototype.setFloat = function (name, value) {
  53747. this._checkUniform(name);
  53748. this._floats[name] = value;
  53749. return this;
  53750. };
  53751. ShaderMaterial.prototype.setInt = function (name, value) {
  53752. this._checkUniform(name);
  53753. this._ints[name] = value;
  53754. return this;
  53755. };
  53756. ShaderMaterial.prototype.setFloats = function (name, value) {
  53757. this._checkUniform(name);
  53758. this._floatsArrays[name] = value;
  53759. return this;
  53760. };
  53761. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53762. this._checkUniform(name);
  53763. this._colors3[name] = value;
  53764. return this;
  53765. };
  53766. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53767. this._checkUniform(name);
  53768. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53769. color.toArray(arr, arr.length);
  53770. return arr;
  53771. }, []);
  53772. return this;
  53773. };
  53774. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53775. this._checkUniform(name);
  53776. this._colors4[name] = value;
  53777. return this;
  53778. };
  53779. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53780. this._checkUniform(name);
  53781. this._vectors2[name] = value;
  53782. return this;
  53783. };
  53784. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53785. this._checkUniform(name);
  53786. this._vectors3[name] = value;
  53787. return this;
  53788. };
  53789. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53790. this._checkUniform(name);
  53791. this._vectors4[name] = value;
  53792. return this;
  53793. };
  53794. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53795. this._checkUniform(name);
  53796. this._matrices[name] = value;
  53797. return this;
  53798. };
  53799. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53800. this._checkUniform(name);
  53801. this._matrices3x3[name] = value;
  53802. return this;
  53803. };
  53804. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53805. this._checkUniform(name);
  53806. this._matrices2x2[name] = value;
  53807. return this;
  53808. };
  53809. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53810. this._checkUniform(name);
  53811. this._vectors2Arrays[name] = value;
  53812. return this;
  53813. };
  53814. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53815. this._checkUniform(name);
  53816. this._vectors3Arrays[name] = value;
  53817. return this;
  53818. };
  53819. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53820. if (!mesh) {
  53821. return true;
  53822. }
  53823. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53824. return false;
  53825. }
  53826. return false;
  53827. };
  53828. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53829. var scene = this.getScene();
  53830. var engine = scene.getEngine();
  53831. if (!this.checkReadyOnEveryCall) {
  53832. if (this._renderId === scene.getRenderId()) {
  53833. if (this._checkCache(scene, mesh, useInstances)) {
  53834. return true;
  53835. }
  53836. }
  53837. }
  53838. // Instances
  53839. var defines = [];
  53840. var attribs = [];
  53841. var fallbacks = new BABYLON.EffectFallbacks();
  53842. if (useInstances) {
  53843. defines.push("#define INSTANCES");
  53844. }
  53845. for (var index = 0; index < this._options.defines.length; index++) {
  53846. defines.push(this._options.defines[index]);
  53847. }
  53848. for (var index = 0; index < this._options.attributes.length; index++) {
  53849. attribs.push(this._options.attributes[index]);
  53850. }
  53851. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53852. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53853. defines.push("#define VERTEXCOLOR");
  53854. }
  53855. // Bones
  53856. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53859. if (mesh.numBoneInfluencers > 4) {
  53860. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53861. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53862. }
  53863. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53864. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53865. fallbacks.addCPUSkinningFallback(0, mesh);
  53866. if (this._options.uniforms.indexOf("mBones") === -1) {
  53867. this._options.uniforms.push("mBones");
  53868. }
  53869. }
  53870. else {
  53871. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53872. }
  53873. // Textures
  53874. for (var name in this._textures) {
  53875. if (!this._textures[name].isReady()) {
  53876. return false;
  53877. }
  53878. }
  53879. // Alpha test
  53880. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53881. defines.push("#define ALPHATEST");
  53882. }
  53883. var previousEffect = this._effect;
  53884. var join = defines.join("\n");
  53885. this._effect = engine.createEffect(this._shaderPath, {
  53886. attributes: attribs,
  53887. uniformsNames: this._options.uniforms,
  53888. uniformBuffersNames: this._options.uniformBuffers,
  53889. samplers: this._options.samplers,
  53890. defines: join,
  53891. fallbacks: fallbacks,
  53892. onCompiled: this.onCompiled,
  53893. onError: this.onError
  53894. }, engine);
  53895. if (!this._effect.isReady()) {
  53896. return false;
  53897. }
  53898. if (previousEffect !== this._effect) {
  53899. scene.resetCachedMaterial();
  53900. }
  53901. this._renderId = scene.getRenderId();
  53902. return true;
  53903. };
  53904. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53905. var scene = this.getScene();
  53906. if (!this._effect) {
  53907. return;
  53908. }
  53909. if (this._options.uniforms.indexOf("world") !== -1) {
  53910. this._effect.setMatrix("world", world);
  53911. }
  53912. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53913. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53914. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53915. }
  53916. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53917. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53918. }
  53919. };
  53920. ShaderMaterial.prototype.bind = function (world, mesh) {
  53921. // Std values
  53922. this.bindOnlyWorldMatrix(world);
  53923. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53924. if (this._options.uniforms.indexOf("view") !== -1) {
  53925. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53926. }
  53927. if (this._options.uniforms.indexOf("projection") !== -1) {
  53928. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53929. }
  53930. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53931. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53932. }
  53933. // Bones
  53934. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53935. var name;
  53936. // Texture
  53937. for (name in this._textures) {
  53938. this._effect.setTexture(name, this._textures[name]);
  53939. }
  53940. // Texture arrays
  53941. for (name in this._textureArrays) {
  53942. this._effect.setTextureArray(name, this._textureArrays[name]);
  53943. }
  53944. // Int
  53945. for (name in this._ints) {
  53946. this._effect.setInt(name, this._ints[name]);
  53947. }
  53948. // Float
  53949. for (name in this._floats) {
  53950. this._effect.setFloat(name, this._floats[name]);
  53951. }
  53952. // Floats
  53953. for (name in this._floatsArrays) {
  53954. this._effect.setArray(name, this._floatsArrays[name]);
  53955. }
  53956. // Color3
  53957. for (name in this._colors3) {
  53958. this._effect.setColor3(name, this._colors3[name]);
  53959. }
  53960. for (name in this._colors3Arrays) {
  53961. this._effect.setArray3(name, this._colors3Arrays[name]);
  53962. }
  53963. // Color4
  53964. for (name in this._colors4) {
  53965. var color = this._colors4[name];
  53966. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53967. }
  53968. // Vector2
  53969. for (name in this._vectors2) {
  53970. this._effect.setVector2(name, this._vectors2[name]);
  53971. }
  53972. // Vector3
  53973. for (name in this._vectors3) {
  53974. this._effect.setVector3(name, this._vectors3[name]);
  53975. }
  53976. // Vector4
  53977. for (name in this._vectors4) {
  53978. this._effect.setVector4(name, this._vectors4[name]);
  53979. }
  53980. // Matrix
  53981. for (name in this._matrices) {
  53982. this._effect.setMatrix(name, this._matrices[name]);
  53983. }
  53984. // Matrix 3x3
  53985. for (name in this._matrices3x3) {
  53986. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53987. }
  53988. // Matrix 2x2
  53989. for (name in this._matrices2x2) {
  53990. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53991. }
  53992. // Vector2Array
  53993. for (name in this._vectors2Arrays) {
  53994. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53995. }
  53996. // Vector3Array
  53997. for (name in this._vectors3Arrays) {
  53998. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53999. }
  54000. }
  54001. this._afterBind(mesh);
  54002. };
  54003. ShaderMaterial.prototype.getActiveTextures = function () {
  54004. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54005. for (var name in this._textures) {
  54006. activeTextures.push(this._textures[name]);
  54007. }
  54008. for (var name in this._textureArrays) {
  54009. var array = this._textureArrays[name];
  54010. for (var index = 0; index < array.length; index++) {
  54011. activeTextures.push(array[index]);
  54012. }
  54013. }
  54014. return activeTextures;
  54015. };
  54016. ShaderMaterial.prototype.hasTexture = function (texture) {
  54017. if (_super.prototype.hasTexture.call(this, texture)) {
  54018. return true;
  54019. }
  54020. for (var name in this._textures) {
  54021. if (this._textures[name] === texture) {
  54022. return true;
  54023. }
  54024. }
  54025. for (var name in this._textureArrays) {
  54026. var array = this._textureArrays[name];
  54027. for (var index = 0; index < array.length; index++) {
  54028. if (array[index] === texture) {
  54029. return true;
  54030. }
  54031. }
  54032. }
  54033. return false;
  54034. };
  54035. ShaderMaterial.prototype.clone = function (name) {
  54036. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54037. return newShaderMaterial;
  54038. };
  54039. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54040. if (forceDisposeTextures) {
  54041. var name;
  54042. for (name in this._textures) {
  54043. this._textures[name].dispose();
  54044. }
  54045. for (name in this._textureArrays) {
  54046. var array = this._textureArrays[name];
  54047. for (var index = 0; index < array.length; index++) {
  54048. array[index].dispose();
  54049. }
  54050. }
  54051. }
  54052. this._textures = {};
  54053. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54054. };
  54055. ShaderMaterial.prototype.serialize = function () {
  54056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54057. serializationObject.customType = "BABYLON.ShaderMaterial";
  54058. serializationObject.options = this._options;
  54059. serializationObject.shaderPath = this._shaderPath;
  54060. var name;
  54061. // Texture
  54062. serializationObject.textures = {};
  54063. for (name in this._textures) {
  54064. serializationObject.textures[name] = this._textures[name].serialize();
  54065. }
  54066. // Texture arrays
  54067. serializationObject.textureArrays = {};
  54068. for (name in this._textureArrays) {
  54069. serializationObject.textureArrays[name] = [];
  54070. var array = this._textureArrays[name];
  54071. for (var index = 0; index < array.length; index++) {
  54072. serializationObject.textureArrays[name].push(array[index].serialize());
  54073. }
  54074. }
  54075. // Float
  54076. serializationObject.floats = {};
  54077. for (name in this._floats) {
  54078. serializationObject.floats[name] = this._floats[name];
  54079. }
  54080. // Float s
  54081. serializationObject.FloatArrays = {};
  54082. for (name in this._floatsArrays) {
  54083. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54084. }
  54085. // Color3
  54086. serializationObject.colors3 = {};
  54087. for (name in this._colors3) {
  54088. serializationObject.colors3[name] = this._colors3[name].asArray();
  54089. }
  54090. // Color3 array
  54091. serializationObject.colors3Arrays = {};
  54092. for (name in this._colors3Arrays) {
  54093. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54094. }
  54095. // Color4
  54096. serializationObject.colors4 = {};
  54097. for (name in this._colors4) {
  54098. serializationObject.colors4[name] = this._colors4[name].asArray();
  54099. }
  54100. // Vector2
  54101. serializationObject.vectors2 = {};
  54102. for (name in this._vectors2) {
  54103. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54104. }
  54105. // Vector3
  54106. serializationObject.vectors3 = {};
  54107. for (name in this._vectors3) {
  54108. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54109. }
  54110. // Vector4
  54111. serializationObject.vectors4 = {};
  54112. for (name in this._vectors4) {
  54113. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54114. }
  54115. // Matrix
  54116. serializationObject.matrices = {};
  54117. for (name in this._matrices) {
  54118. serializationObject.matrices[name] = this._matrices[name].asArray();
  54119. }
  54120. // Matrix 3x3
  54121. serializationObject.matrices3x3 = {};
  54122. for (name in this._matrices3x3) {
  54123. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54124. }
  54125. // Matrix 2x2
  54126. serializationObject.matrices2x2 = {};
  54127. for (name in this._matrices2x2) {
  54128. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54129. }
  54130. // Vector2Array
  54131. serializationObject.vectors2Arrays = {};
  54132. for (name in this._vectors2Arrays) {
  54133. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54134. }
  54135. // Vector3Array
  54136. serializationObject.vectors3Arrays = {};
  54137. for (name in this._vectors3Arrays) {
  54138. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54139. }
  54140. return serializationObject;
  54141. };
  54142. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54143. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54144. var name;
  54145. // Texture
  54146. for (name in source.textures) {
  54147. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54148. }
  54149. // Texture arrays
  54150. for (name in source.textureArrays) {
  54151. var array = source.textureArrays[name];
  54152. var textureArray = new Array();
  54153. for (var index = 0; index < array.length; index++) {
  54154. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54155. }
  54156. material.setTextureArray(name, textureArray);
  54157. }
  54158. // Float
  54159. for (name in source.floats) {
  54160. material.setFloat(name, source.floats[name]);
  54161. }
  54162. // Float s
  54163. for (name in source.floatsArrays) {
  54164. material.setFloats(name, source.floatsArrays[name]);
  54165. }
  54166. // Color3
  54167. for (name in source.colors3) {
  54168. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54169. }
  54170. // Color3 arrays
  54171. for (name in source.colors3Arrays) {
  54172. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54173. if (i % 3 === 0) {
  54174. arr.push([num]);
  54175. }
  54176. else {
  54177. arr[arr.length - 1].push(num);
  54178. }
  54179. return arr;
  54180. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54181. material.setColor3Array(name, colors);
  54182. }
  54183. // Color4
  54184. for (name in source.colors4) {
  54185. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54186. }
  54187. // Vector2
  54188. for (name in source.vectors2) {
  54189. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54190. }
  54191. // Vector3
  54192. for (name in source.vectors3) {
  54193. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54194. }
  54195. // Vector4
  54196. for (name in source.vectors4) {
  54197. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54198. }
  54199. // Matrix
  54200. for (name in source.matrices) {
  54201. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54202. }
  54203. // Matrix 3x3
  54204. for (name in source.matrices3x3) {
  54205. material.setMatrix3x3(name, source.matrices3x3[name]);
  54206. }
  54207. // Matrix 2x2
  54208. for (name in source.matrices2x2) {
  54209. material.setMatrix2x2(name, source.matrices2x2[name]);
  54210. }
  54211. // Vector2Array
  54212. for (name in source.vectors2Arrays) {
  54213. material.setArray2(name, source.vectors2Arrays[name]);
  54214. }
  54215. // Vector3Array
  54216. for (name in source.vectors3Arrays) {
  54217. material.setArray3(name, source.vectors3Arrays[name]);
  54218. }
  54219. return material;
  54220. };
  54221. return ShaderMaterial;
  54222. }(BABYLON.Material));
  54223. BABYLON.ShaderMaterial = ShaderMaterial;
  54224. })(BABYLON || (BABYLON = {}));
  54225. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54226. var BABYLON;
  54227. (function (BABYLON) {
  54228. var GroundMesh = /** @class */ (function (_super) {
  54229. __extends(GroundMesh, _super);
  54230. function GroundMesh(name, scene) {
  54231. var _this = _super.call(this, name, scene) || this;
  54232. _this.generateOctree = false;
  54233. return _this;
  54234. }
  54235. GroundMesh.prototype.getClassName = function () {
  54236. return "GroundMesh";
  54237. };
  54238. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54239. get: function () {
  54240. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54241. },
  54242. enumerable: true,
  54243. configurable: true
  54244. });
  54245. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54246. get: function () {
  54247. return this._subdivisionsX;
  54248. },
  54249. enumerable: true,
  54250. configurable: true
  54251. });
  54252. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54253. get: function () {
  54254. return this._subdivisionsY;
  54255. },
  54256. enumerable: true,
  54257. configurable: true
  54258. });
  54259. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54260. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54261. this._subdivisionsX = chunksCount;
  54262. this._subdivisionsY = chunksCount;
  54263. this.subdivide(chunksCount);
  54264. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54265. };
  54266. /**
  54267. * Returns a height (y) value in the Worl system :
  54268. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54269. * Returns the ground y position if (x, z) are outside the ground surface.
  54270. */
  54271. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54272. var world = this.getWorldMatrix();
  54273. var invMat = BABYLON.Tmp.Matrix[5];
  54274. world.invertToRef(invMat);
  54275. var tmpVect = BABYLON.Tmp.Vector3[8];
  54276. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54277. x = tmpVect.x;
  54278. z = tmpVect.z;
  54279. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54280. return this.position.y;
  54281. }
  54282. if (!this._heightQuads || this._heightQuads.length == 0) {
  54283. this._initHeightQuads();
  54284. this._computeHeightQuads();
  54285. }
  54286. var facet = this._getFacetAt(x, z);
  54287. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54288. // return y in the World system
  54289. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54290. return tmpVect.y;
  54291. };
  54292. /**
  54293. * Returns a normalized vector (Vector3) orthogonal to the ground
  54294. * at the ground coordinates (x, z) expressed in the World system.
  54295. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54296. */
  54297. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54298. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54299. this.getNormalAtCoordinatesToRef(x, z, normal);
  54300. return normal;
  54301. };
  54302. /**
  54303. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54304. * at the ground coordinates (x, z) expressed in the World system.
  54305. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54306. * Returns the GroundMesh.
  54307. */
  54308. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54309. var world = this.getWorldMatrix();
  54310. var tmpMat = BABYLON.Tmp.Matrix[5];
  54311. world.invertToRef(tmpMat);
  54312. var tmpVect = BABYLON.Tmp.Vector3[8];
  54313. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54314. x = tmpVect.x;
  54315. z = tmpVect.z;
  54316. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54317. return this;
  54318. }
  54319. if (!this._heightQuads || this._heightQuads.length == 0) {
  54320. this._initHeightQuads();
  54321. this._computeHeightQuads();
  54322. }
  54323. var facet = this._getFacetAt(x, z);
  54324. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54325. return this;
  54326. };
  54327. /**
  54328. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54329. * if the ground has been updated.
  54330. * This can be used in the render loop.
  54331. * Returns the GroundMesh.
  54332. */
  54333. GroundMesh.prototype.updateCoordinateHeights = function () {
  54334. if (!this._heightQuads || this._heightQuads.length == 0) {
  54335. this._initHeightQuads();
  54336. }
  54337. this._computeHeightQuads();
  54338. return this;
  54339. };
  54340. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54341. GroundMesh.prototype._getFacetAt = function (x, z) {
  54342. // retrieve col and row from x, z coordinates in the ground local system
  54343. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54344. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54345. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54346. var facet;
  54347. if (z < quad.slope.x * x + quad.slope.y) {
  54348. facet = quad.facet1;
  54349. }
  54350. else {
  54351. facet = quad.facet2;
  54352. }
  54353. return facet;
  54354. };
  54355. // Creates and populates the heightMap array with "facet" elements :
  54356. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54357. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54358. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54359. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54360. // Returns the GroundMesh.
  54361. GroundMesh.prototype._initHeightQuads = function () {
  54362. var subdivisionsX = this._subdivisionsX;
  54363. var subdivisionsY = this._subdivisionsY;
  54364. this._heightQuads = new Array();
  54365. for (var row = 0; row < subdivisionsY; row++) {
  54366. for (var col = 0; col < subdivisionsX; col++) {
  54367. 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) };
  54368. this._heightQuads[row * subdivisionsX + col] = quad;
  54369. }
  54370. }
  54371. return this;
  54372. };
  54373. // Compute each quad element values and update the the heightMap array :
  54374. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54375. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54376. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54377. // Returns the GroundMesh.
  54378. GroundMesh.prototype._computeHeightQuads = function () {
  54379. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54380. if (!positions) {
  54381. return this;
  54382. }
  54383. var v1 = BABYLON.Tmp.Vector3[3];
  54384. var v2 = BABYLON.Tmp.Vector3[2];
  54385. var v3 = BABYLON.Tmp.Vector3[1];
  54386. var v4 = BABYLON.Tmp.Vector3[0];
  54387. var v1v2 = BABYLON.Tmp.Vector3[4];
  54388. var v1v3 = BABYLON.Tmp.Vector3[5];
  54389. var v1v4 = BABYLON.Tmp.Vector3[6];
  54390. var norm1 = BABYLON.Tmp.Vector3[7];
  54391. var norm2 = BABYLON.Tmp.Vector3[8];
  54392. var i = 0;
  54393. var j = 0;
  54394. var k = 0;
  54395. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54396. var h = 0;
  54397. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54398. var d2 = 0;
  54399. var subdivisionsX = this._subdivisionsX;
  54400. var subdivisionsY = this._subdivisionsY;
  54401. for (var row = 0; row < subdivisionsY; row++) {
  54402. for (var col = 0; col < subdivisionsX; col++) {
  54403. i = col * 3;
  54404. j = row * (subdivisionsX + 1) * 3;
  54405. k = (row + 1) * (subdivisionsX + 1) * 3;
  54406. v1.x = positions[j + i];
  54407. v1.y = positions[j + i + 1];
  54408. v1.z = positions[j + i + 2];
  54409. v2.x = positions[j + i + 3];
  54410. v2.y = positions[j + i + 4];
  54411. v2.z = positions[j + i + 5];
  54412. v3.x = positions[k + i];
  54413. v3.y = positions[k + i + 1];
  54414. v3.z = positions[k + i + 2];
  54415. v4.x = positions[k + i + 3];
  54416. v4.y = positions[k + i + 4];
  54417. v4.z = positions[k + i + 5];
  54418. // 2D slope V1V4
  54419. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54420. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54421. // facet equations :
  54422. // we compute each facet normal vector
  54423. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54424. // we compute the value d by applying the equation to v1 which belongs to the plane
  54425. // then we store the facet equation in a Vector4
  54426. v2.subtractToRef(v1, v1v2);
  54427. v3.subtractToRef(v1, v1v3);
  54428. v4.subtractToRef(v1, v1v4);
  54429. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54430. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54431. norm1.normalize();
  54432. norm2.normalize();
  54433. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54434. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54435. var quad = this._heightQuads[row * subdivisionsX + col];
  54436. quad.slope.copyFromFloats(cd, h);
  54437. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54438. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54439. }
  54440. }
  54441. return this;
  54442. };
  54443. GroundMesh.prototype.serialize = function (serializationObject) {
  54444. _super.prototype.serialize.call(this, serializationObject);
  54445. serializationObject.subdivisionsX = this._subdivisionsX;
  54446. serializationObject.subdivisionsY = this._subdivisionsY;
  54447. serializationObject.minX = this._minX;
  54448. serializationObject.maxX = this._maxX;
  54449. serializationObject.minZ = this._minZ;
  54450. serializationObject.maxZ = this._maxZ;
  54451. serializationObject.width = this._width;
  54452. serializationObject.height = this._height;
  54453. };
  54454. GroundMesh.Parse = function (parsedMesh, scene) {
  54455. var result = new GroundMesh(parsedMesh.name, scene);
  54456. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54457. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54458. result._minX = parsedMesh.minX;
  54459. result._maxX = parsedMesh.maxX;
  54460. result._minZ = parsedMesh.minZ;
  54461. result._maxZ = parsedMesh.maxZ;
  54462. result._width = parsedMesh.width;
  54463. result._height = parsedMesh.height;
  54464. return result;
  54465. };
  54466. return GroundMesh;
  54467. }(BABYLON.Mesh));
  54468. BABYLON.GroundMesh = GroundMesh;
  54469. })(BABYLON || (BABYLON = {}));
  54470. //# sourceMappingURL=babylon.groundMesh.js.map
  54471. var BABYLON;
  54472. (function (BABYLON) {
  54473. /**
  54474. * Creates an instance based on a source mesh.
  54475. */
  54476. var InstancedMesh = /** @class */ (function (_super) {
  54477. __extends(InstancedMesh, _super);
  54478. function InstancedMesh(name, source) {
  54479. var _this = _super.call(this, name, source.getScene()) || this;
  54480. source.instances.push(_this);
  54481. _this._sourceMesh = source;
  54482. _this.position.copyFrom(source.position);
  54483. _this.rotation.copyFrom(source.rotation);
  54484. _this.scaling.copyFrom(source.scaling);
  54485. if (source.rotationQuaternion) {
  54486. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54487. }
  54488. _this.infiniteDistance = source.infiniteDistance;
  54489. _this.setPivotMatrix(source.getPivotMatrix());
  54490. _this.refreshBoundingInfo();
  54491. _this._syncSubMeshes();
  54492. return _this;
  54493. }
  54494. /**
  54495. * Returns the string "InstancedMesh".
  54496. */
  54497. InstancedMesh.prototype.getClassName = function () {
  54498. return "InstancedMesh";
  54499. };
  54500. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54501. // Methods
  54502. get: function () {
  54503. return this._sourceMesh.receiveShadows;
  54504. },
  54505. enumerable: true,
  54506. configurable: true
  54507. });
  54508. Object.defineProperty(InstancedMesh.prototype, "material", {
  54509. get: function () {
  54510. return this._sourceMesh.material;
  54511. },
  54512. enumerable: true,
  54513. configurable: true
  54514. });
  54515. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54516. get: function () {
  54517. return this._sourceMesh.visibility;
  54518. },
  54519. enumerable: true,
  54520. configurable: true
  54521. });
  54522. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54523. get: function () {
  54524. return this._sourceMesh.skeleton;
  54525. },
  54526. enumerable: true,
  54527. configurable: true
  54528. });
  54529. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54530. get: function () {
  54531. return this._sourceMesh.renderingGroupId;
  54532. },
  54533. set: function (value) {
  54534. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  54535. return;
  54536. }
  54537. //no-op with warning
  54538. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  54539. },
  54540. enumerable: true,
  54541. configurable: true
  54542. });
  54543. /**
  54544. * Returns the total number of vertices (integer).
  54545. */
  54546. InstancedMesh.prototype.getTotalVertices = function () {
  54547. return this._sourceMesh.getTotalVertices();
  54548. };
  54549. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54550. get: function () {
  54551. return this._sourceMesh;
  54552. },
  54553. enumerable: true,
  54554. configurable: true
  54555. });
  54556. /**
  54557. * Is this node ready to be used/rendered
  54558. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54559. * @return {boolean} is it ready
  54560. */
  54561. InstancedMesh.prototype.isReady = function (completeCheck) {
  54562. if (completeCheck === void 0) { completeCheck = false; }
  54563. return this._sourceMesh.isReady(completeCheck, true);
  54564. };
  54565. /**
  54566. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54567. */
  54568. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54569. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54570. };
  54571. /**
  54572. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54573. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54574. * The `data` are either a numeric array either a Float32Array.
  54575. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54576. * 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).
  54577. * Note that a new underlying VertexBuffer object is created each call.
  54578. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54579. *
  54580. * Possible `kind` values :
  54581. * - BABYLON.VertexBuffer.PositionKind
  54582. * - BABYLON.VertexBuffer.UVKind
  54583. * - BABYLON.VertexBuffer.UV2Kind
  54584. * - BABYLON.VertexBuffer.UV3Kind
  54585. * - BABYLON.VertexBuffer.UV4Kind
  54586. * - BABYLON.VertexBuffer.UV5Kind
  54587. * - BABYLON.VertexBuffer.UV6Kind
  54588. * - BABYLON.VertexBuffer.ColorKind
  54589. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54590. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54591. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54592. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54593. *
  54594. * Returns the Mesh.
  54595. */
  54596. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54597. if (this.sourceMesh) {
  54598. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54599. }
  54600. return this.sourceMesh;
  54601. };
  54602. /**
  54603. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54604. * If the mesh has no geometry, it is simply returned as it is.
  54605. * The `data` are either a numeric array either a Float32Array.
  54606. * No new underlying VertexBuffer object is created.
  54607. * 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.
  54608. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54609. *
  54610. * Possible `kind` values :
  54611. * - BABYLON.VertexBuffer.PositionKind
  54612. * - BABYLON.VertexBuffer.UVKind
  54613. * - BABYLON.VertexBuffer.UV2Kind
  54614. * - BABYLON.VertexBuffer.UV3Kind
  54615. * - BABYLON.VertexBuffer.UV4Kind
  54616. * - BABYLON.VertexBuffer.UV5Kind
  54617. * - BABYLON.VertexBuffer.UV6Kind
  54618. * - BABYLON.VertexBuffer.ColorKind
  54619. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54620. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54621. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54622. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54623. *
  54624. * Returns the Mesh.
  54625. */
  54626. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54627. if (this.sourceMesh) {
  54628. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54629. }
  54630. return this.sourceMesh;
  54631. };
  54632. /**
  54633. * Sets the mesh indices.
  54634. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54635. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54636. * This method creates a new index buffer each call.
  54637. * Returns the Mesh.
  54638. */
  54639. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54640. if (totalVertices === void 0) { totalVertices = null; }
  54641. if (this.sourceMesh) {
  54642. this.sourceMesh.setIndices(indices, totalVertices);
  54643. }
  54644. return this.sourceMesh;
  54645. };
  54646. /**
  54647. * Boolean : True if the mesh owns the requested kind of data.
  54648. */
  54649. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54650. return this._sourceMesh.isVerticesDataPresent(kind);
  54651. };
  54652. /**
  54653. * Returns an array of indices (IndicesArray).
  54654. */
  54655. InstancedMesh.prototype.getIndices = function () {
  54656. return this._sourceMesh.getIndices();
  54657. };
  54658. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54659. get: function () {
  54660. return this._sourceMesh._positions;
  54661. },
  54662. enumerable: true,
  54663. configurable: true
  54664. });
  54665. /**
  54666. * Sets a new updated BoundingInfo to the mesh.
  54667. * Returns the mesh.
  54668. */
  54669. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54670. var meshBB = this._sourceMesh.getBoundingInfo();
  54671. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54672. this._updateBoundingInfo();
  54673. return this;
  54674. };
  54675. InstancedMesh.prototype._preActivate = function () {
  54676. if (this._currentLOD) {
  54677. this._currentLOD._preActivate();
  54678. }
  54679. return this;
  54680. };
  54681. InstancedMesh.prototype._activate = function (renderId) {
  54682. if (this._currentLOD) {
  54683. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54684. }
  54685. return this;
  54686. };
  54687. /**
  54688. * Returns the current associated LOD AbstractMesh.
  54689. */
  54690. InstancedMesh.prototype.getLOD = function (camera) {
  54691. if (!camera) {
  54692. return this;
  54693. }
  54694. var boundingInfo = this.getBoundingInfo();
  54695. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54696. if (this._currentLOD === this.sourceMesh) {
  54697. return this;
  54698. }
  54699. return this._currentLOD;
  54700. };
  54701. InstancedMesh.prototype._syncSubMeshes = function () {
  54702. this.releaseSubMeshes();
  54703. if (this._sourceMesh.subMeshes) {
  54704. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54705. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54706. }
  54707. }
  54708. return this;
  54709. };
  54710. InstancedMesh.prototype._generatePointsArray = function () {
  54711. return this._sourceMesh._generatePointsArray();
  54712. };
  54713. /**
  54714. * Creates a new InstancedMesh from the current mesh.
  54715. * - name (string) : the cloned mesh name
  54716. * - newParent (optional Node) : the optional Node to parent the clone to.
  54717. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54718. *
  54719. * Returns the clone.
  54720. */
  54721. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54722. var result = this._sourceMesh.createInstance(name);
  54723. // Deep copy
  54724. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54725. // Bounding info
  54726. this.refreshBoundingInfo();
  54727. // Parent
  54728. if (newParent) {
  54729. result.parent = newParent;
  54730. }
  54731. if (!doNotCloneChildren) {
  54732. // Children
  54733. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54734. var mesh = this.getScene().meshes[index];
  54735. if (mesh.parent === this) {
  54736. mesh.clone(mesh.name, result);
  54737. }
  54738. }
  54739. }
  54740. result.computeWorldMatrix(true);
  54741. return result;
  54742. };
  54743. /**
  54744. * Disposes the InstancedMesh.
  54745. * Returns nothing.
  54746. */
  54747. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  54748. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  54749. // Remove from mesh
  54750. var index = this._sourceMesh.instances.indexOf(this);
  54751. this._sourceMesh.instances.splice(index, 1);
  54752. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  54753. };
  54754. return InstancedMesh;
  54755. }(BABYLON.AbstractMesh));
  54756. BABYLON.InstancedMesh = InstancedMesh;
  54757. })(BABYLON || (BABYLON = {}));
  54758. //# sourceMappingURL=babylon.instancedMesh.js.map
  54759. var BABYLON;
  54760. (function (BABYLON) {
  54761. var LinesMesh = /** @class */ (function (_super) {
  54762. __extends(LinesMesh, _super);
  54763. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54764. if (scene === void 0) { scene = null; }
  54765. if (parent === void 0) { parent = null; }
  54766. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54767. _this.useVertexColor = useVertexColor;
  54768. _this.useVertexAlpha = useVertexAlpha;
  54769. _this.color = new BABYLON.Color3(1, 1, 1);
  54770. _this.alpha = 1;
  54771. if (source) {
  54772. _this.color = source.color.clone();
  54773. _this.alpha = source.alpha;
  54774. _this.useVertexColor = source.useVertexColor;
  54775. _this.useVertexAlpha = source.useVertexAlpha;
  54776. }
  54777. _this._intersectionThreshold = 0.1;
  54778. var defines = [];
  54779. var options = {
  54780. attributes: [BABYLON.VertexBuffer.PositionKind],
  54781. uniforms: ["world", "viewProjection"],
  54782. needAlphaBlending: true,
  54783. defines: defines
  54784. };
  54785. if (useVertexAlpha === false) {
  54786. options.needAlphaBlending = false;
  54787. }
  54788. if (!useVertexColor) {
  54789. options.uniforms.push("color");
  54790. }
  54791. else {
  54792. options.defines.push("#define VERTEXCOLOR");
  54793. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54794. }
  54795. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54796. return _this;
  54797. }
  54798. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54799. /**
  54800. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54801. * This margin is expressed in world space coordinates, so its value may vary.
  54802. * Default value is 0.1
  54803. * @returns the intersection Threshold value.
  54804. */
  54805. get: function () {
  54806. return this._intersectionThreshold;
  54807. },
  54808. /**
  54809. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54810. * This margin is expressed in world space coordinates, so its value may vary.
  54811. * @param value the new threshold to apply
  54812. */
  54813. set: function (value) {
  54814. if (this._intersectionThreshold === value) {
  54815. return;
  54816. }
  54817. this._intersectionThreshold = value;
  54818. if (this.geometry) {
  54819. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54820. }
  54821. },
  54822. enumerable: true,
  54823. configurable: true
  54824. });
  54825. /**
  54826. * Returns the string "LineMesh"
  54827. */
  54828. LinesMesh.prototype.getClassName = function () {
  54829. return "LinesMesh";
  54830. };
  54831. Object.defineProperty(LinesMesh.prototype, "material", {
  54832. get: function () {
  54833. return this._colorShader;
  54834. },
  54835. set: function (value) {
  54836. // Do nothing
  54837. },
  54838. enumerable: true,
  54839. configurable: true
  54840. });
  54841. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54842. get: function () {
  54843. return false;
  54844. },
  54845. enumerable: true,
  54846. configurable: true
  54847. });
  54848. LinesMesh.prototype.createInstance = function (name) {
  54849. throw new Error("LinesMeshes do not support createInstance.");
  54850. };
  54851. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54852. if (!this._geometry) {
  54853. return this;
  54854. }
  54855. // VBOs
  54856. this._geometry._bind(this._colorShader.getEffect());
  54857. // Color
  54858. if (!this.useVertexColor) {
  54859. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54860. }
  54861. return this;
  54862. };
  54863. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54864. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54865. return this;
  54866. }
  54867. var engine = this.getScene().getEngine();
  54868. // Draw order
  54869. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54870. return this;
  54871. };
  54872. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54873. this._colorShader.dispose();
  54874. _super.prototype.dispose.call(this, doNotRecurse);
  54875. };
  54876. /**
  54877. * Returns a new LineMesh object cloned from the current one.
  54878. */
  54879. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54880. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54881. };
  54882. return LinesMesh;
  54883. }(BABYLON.Mesh));
  54884. BABYLON.LinesMesh = LinesMesh;
  54885. })(BABYLON || (BABYLON = {}));
  54886. //# sourceMappingURL=babylon.linesMesh.js.map
  54887. var BABYLON;
  54888. (function (BABYLON) {
  54889. var MeshBuilder = /** @class */ (function () {
  54890. function MeshBuilder() {
  54891. }
  54892. MeshBuilder.updateSideOrientation = function (orientation) {
  54893. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54894. return BABYLON.Mesh.DOUBLESIDE;
  54895. }
  54896. if (orientation === undefined || orientation === null) {
  54897. return BABYLON.Mesh.FRONTSIDE;
  54898. }
  54899. return orientation;
  54900. };
  54901. /**
  54902. * Creates a box mesh.
  54903. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54904. * The parameter `size` sets the size (float) of each box side (default 1).
  54905. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54906. * 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).
  54907. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54908. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54909. * 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).
  54910. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54912. */
  54913. MeshBuilder.CreateBox = function (name, options, scene) {
  54914. if (scene === void 0) { scene = null; }
  54915. var box = new BABYLON.Mesh(name, scene);
  54916. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54917. box._originalBuilderSideOrientation = options.sideOrientation;
  54918. var vertexData = BABYLON.VertexData.CreateBox(options);
  54919. vertexData.applyToMesh(box, options.updatable);
  54920. return box;
  54921. };
  54922. /**
  54923. * Creates a sphere mesh.
  54924. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54925. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54926. * 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`).
  54927. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54928. * 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
  54929. * 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).
  54930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54931. * 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).
  54932. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54933. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54934. */
  54935. MeshBuilder.CreateSphere = function (name, options, scene) {
  54936. var sphere = new BABYLON.Mesh(name, scene);
  54937. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54938. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54939. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54940. vertexData.applyToMesh(sphere, options.updatable);
  54941. return sphere;
  54942. };
  54943. /**
  54944. * Creates a plane polygonal mesh. By default, this is a disc.
  54945. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54946. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54947. * 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.
  54948. * 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
  54949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54950. * 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).
  54951. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54953. */
  54954. MeshBuilder.CreateDisc = function (name, options, scene) {
  54955. if (scene === void 0) { scene = null; }
  54956. var disc = new BABYLON.Mesh(name, scene);
  54957. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54958. disc._originalBuilderSideOrientation = options.sideOrientation;
  54959. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54960. vertexData.applyToMesh(disc, options.updatable);
  54961. return disc;
  54962. };
  54963. /**
  54964. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54965. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54966. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54967. * 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`).
  54968. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54969. * 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.
  54970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54971. * 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).
  54972. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54974. */
  54975. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54976. var sphere = new BABYLON.Mesh(name, scene);
  54977. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54978. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54979. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54980. vertexData.applyToMesh(sphere, options.updatable);
  54981. return sphere;
  54982. };
  54983. ;
  54984. /**
  54985. * Creates a ribbon mesh.
  54986. * 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.
  54987. *
  54988. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54989. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54990. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54991. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54992. * 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.
  54993. * 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.
  54994. * 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
  54995. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54996. * 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).
  54997. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54998. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54999. * 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.
  55000. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55001. * 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
  55002. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55003. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55004. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55005. */
  55006. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55007. if (scene === void 0) { scene = null; }
  55008. var pathArray = options.pathArray;
  55009. var closeArray = options.closeArray;
  55010. var closePath = options.closePath;
  55011. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55012. var instance = options.instance;
  55013. var updatable = options.updatable;
  55014. if (instance) {
  55015. // positionFunction : ribbon case
  55016. // only pathArray and sideOrientation parameters are taken into account for positions update
  55017. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55018. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55019. var positionFunction = function (positions) {
  55020. var minlg = pathArray[0].length;
  55021. var i = 0;
  55022. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55023. for (var si = 1; si <= ns; si++) {
  55024. for (var p = 0; p < pathArray.length; p++) {
  55025. var path = pathArray[p];
  55026. var l = path.length;
  55027. minlg = (minlg < l) ? minlg : l;
  55028. var j = 0;
  55029. while (j < minlg) {
  55030. positions[i] = path[j].x;
  55031. positions[i + 1] = path[j].y;
  55032. positions[i + 2] = path[j].z;
  55033. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55034. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55035. }
  55036. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55037. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55038. }
  55039. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55040. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55041. }
  55042. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55043. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55044. }
  55045. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55046. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55047. }
  55048. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55049. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55050. }
  55051. j++;
  55052. i += 3;
  55053. }
  55054. if (instance._closePath) {
  55055. positions[i] = path[0].x;
  55056. positions[i + 1] = path[0].y;
  55057. positions[i + 2] = path[0].z;
  55058. i += 3;
  55059. }
  55060. }
  55061. }
  55062. };
  55063. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55064. positionFunction(positions);
  55065. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55066. instance._boundingInfo.update(instance._worldMatrix);
  55067. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55068. if (options.colors) {
  55069. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55070. for (var c = 0; c < options.colors.length; c++) {
  55071. colors[c * 4] = options.colors[c].r;
  55072. colors[c * 4 + 1] = options.colors[c].g;
  55073. colors[c * 4 + 2] = options.colors[c].b;
  55074. colors[c * 4 + 3] = options.colors[c].a;
  55075. }
  55076. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55077. }
  55078. if (options.uvs) {
  55079. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55080. for (var i = 0; i < options.uvs.length; i++) {
  55081. uvs[i * 2] = options.uvs[i].x;
  55082. uvs[i * 2 + 1] = options.uvs[i].y;
  55083. }
  55084. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55085. }
  55086. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55087. var indices = instance.getIndices();
  55088. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55089. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55090. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55091. if (instance._closePath) {
  55092. var indexFirst = 0;
  55093. var indexLast = 0;
  55094. for (var p = 0; p < pathArray.length; p++) {
  55095. indexFirst = instance._idx[p] * 3;
  55096. if (p + 1 < pathArray.length) {
  55097. indexLast = (instance._idx[p + 1] - 1) * 3;
  55098. }
  55099. else {
  55100. indexLast = normals.length - 3;
  55101. }
  55102. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55103. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55104. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55105. normals[indexLast] = normals[indexFirst];
  55106. normals[indexLast + 1] = normals[indexFirst + 1];
  55107. normals[indexLast + 2] = normals[indexFirst + 2];
  55108. }
  55109. }
  55110. if (!(instance.areNormalsFrozen)) {
  55111. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55112. }
  55113. }
  55114. return instance;
  55115. }
  55116. else {
  55117. var ribbon = new BABYLON.Mesh(name, scene);
  55118. ribbon._originalBuilderSideOrientation = sideOrientation;
  55119. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55120. if (closePath) {
  55121. ribbon._idx = vertexData._idx;
  55122. }
  55123. ribbon._closePath = closePath;
  55124. ribbon._closeArray = closeArray;
  55125. vertexData.applyToMesh(ribbon, updatable);
  55126. return ribbon;
  55127. }
  55128. };
  55129. /**
  55130. * Creates a cylinder or a cone mesh.
  55131. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55132. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55133. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55134. * 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.
  55135. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55136. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55137. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55138. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55139. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55140. * 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).
  55141. * 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
  55142. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55143. * 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
  55144. * 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.
  55145. * If `enclose` is false, a ring surface is one element.
  55146. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55147. * 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
  55148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55149. * 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).
  55150. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55152. */
  55153. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55154. var cylinder = new BABYLON.Mesh(name, scene);
  55155. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55156. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55157. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55158. vertexData.applyToMesh(cylinder, options.updatable);
  55159. return cylinder;
  55160. };
  55161. /**
  55162. * Creates a torus mesh.
  55163. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55164. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55165. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55166. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55168. * 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).
  55169. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55170. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55171. */
  55172. MeshBuilder.CreateTorus = function (name, options, scene) {
  55173. var torus = new BABYLON.Mesh(name, scene);
  55174. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55175. torus._originalBuilderSideOrientation = options.sideOrientation;
  55176. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55177. vertexData.applyToMesh(torus, options.updatable);
  55178. return torus;
  55179. };
  55180. /**
  55181. * Creates a torus knot mesh.
  55182. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55183. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55184. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55185. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55186. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55187. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55188. * 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).
  55189. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55191. */
  55192. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55193. var torusKnot = new BABYLON.Mesh(name, scene);
  55194. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55195. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55196. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55197. vertexData.applyToMesh(torusKnot, options.updatable);
  55198. return torusKnot;
  55199. };
  55200. /**
  55201. * Creates a line system mesh.
  55202. * A line system is a pool of many lines gathered in a single mesh.
  55203. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55204. * 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.
  55205. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55206. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55207. * 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
  55208. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55209. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55210. * 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
  55211. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55213. */
  55214. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55215. var instance = options.instance;
  55216. var lines = options.lines;
  55217. var colors = options.colors;
  55218. if (instance) {
  55219. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55220. var vertexColor;
  55221. var lineColors;
  55222. if (colors) {
  55223. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55224. }
  55225. var i = 0;
  55226. var c = 0;
  55227. for (var l = 0; l < lines.length; l++) {
  55228. var points = lines[l];
  55229. for (var p = 0; p < points.length; p++) {
  55230. positions[i] = points[p].x;
  55231. positions[i + 1] = points[p].y;
  55232. positions[i + 2] = points[p].z;
  55233. if (colors && vertexColor) {
  55234. lineColors = colors[l];
  55235. vertexColor[c] = lineColors[p].r;
  55236. vertexColor[c + 1] = lineColors[p].g;
  55237. vertexColor[c + 2] = lineColors[p].b;
  55238. vertexColor[c + 3] = lineColors[p].a;
  55239. c += 4;
  55240. }
  55241. i += 3;
  55242. }
  55243. }
  55244. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55245. if (colors && vertexColor) {
  55246. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55247. }
  55248. return instance;
  55249. }
  55250. // line system creation
  55251. var useVertexColor = (colors) ? true : false;
  55252. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55253. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55254. vertexData.applyToMesh(lineSystem, options.updatable);
  55255. return lineSystem;
  55256. };
  55257. /**
  55258. * Creates a line mesh.
  55259. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55260. * 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.
  55261. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55262. * The parameter `points` is an array successive Vector3.
  55263. * 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
  55264. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55265. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55266. * When updating an instance, remember that only point positions can change, not the number of points.
  55267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55268. */
  55269. MeshBuilder.CreateLines = function (name, options, scene) {
  55270. if (scene === void 0) { scene = null; }
  55271. var colors = (options.colors) ? [options.colors] : null;
  55272. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55273. return lines;
  55274. };
  55275. /**
  55276. * Creates a dashed line mesh.
  55277. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55278. * 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.
  55279. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55280. * The parameter `points` is an array successive Vector3.
  55281. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55282. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55283. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55284. * 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
  55285. * When updating an instance, remember that only point positions can change, not the number of points.
  55286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55287. */
  55288. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55289. if (scene === void 0) { scene = null; }
  55290. var points = options.points;
  55291. var instance = options.instance;
  55292. var gapSize = options.gapSize || 1;
  55293. var dashSize = options.dashSize || 3;
  55294. if (instance) {
  55295. var positionFunction = function (positions) {
  55296. var curvect = BABYLON.Vector3.Zero();
  55297. var nbSeg = positions.length / 6;
  55298. var lg = 0;
  55299. var nb = 0;
  55300. var shft = 0;
  55301. var dashshft = 0;
  55302. var curshft = 0;
  55303. var p = 0;
  55304. var i = 0;
  55305. var j = 0;
  55306. for (i = 0; i < points.length - 1; i++) {
  55307. points[i + 1].subtractToRef(points[i], curvect);
  55308. lg += curvect.length();
  55309. }
  55310. shft = lg / nbSeg;
  55311. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55312. for (i = 0; i < points.length - 1; i++) {
  55313. points[i + 1].subtractToRef(points[i], curvect);
  55314. nb = Math.floor(curvect.length() / shft);
  55315. curvect.normalize();
  55316. j = 0;
  55317. while (j < nb && p < positions.length) {
  55318. curshft = shft * j;
  55319. positions[p] = points[i].x + curshft * curvect.x;
  55320. positions[p + 1] = points[i].y + curshft * curvect.y;
  55321. positions[p + 2] = points[i].z + curshft * curvect.z;
  55322. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55323. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55324. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55325. p += 6;
  55326. j++;
  55327. }
  55328. }
  55329. while (p < positions.length) {
  55330. positions[p] = points[i].x;
  55331. positions[p + 1] = points[i].y;
  55332. positions[p + 2] = points[i].z;
  55333. p += 3;
  55334. }
  55335. };
  55336. instance.updateMeshPositions(positionFunction, false);
  55337. return instance;
  55338. }
  55339. // dashed lines creation
  55340. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55341. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55342. vertexData.applyToMesh(dashedLines, options.updatable);
  55343. dashedLines.dashSize = dashSize;
  55344. dashedLines.gapSize = gapSize;
  55345. return dashedLines;
  55346. };
  55347. /**
  55348. * Creates an extruded shape mesh.
  55349. * 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.
  55350. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55351. *
  55352. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55353. * 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
  55354. * extruded along the Z axis.
  55355. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55356. * 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.
  55357. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55358. * 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
  55359. * 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
  55360. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55362. * 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).
  55363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55364. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55366. */
  55367. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55368. if (scene === void 0) { scene = null; }
  55369. var path = options.path;
  55370. var shape = options.shape;
  55371. var scale = options.scale || 1;
  55372. var rotation = options.rotation || 0;
  55373. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55374. var updatable = options.updatable;
  55375. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55376. var instance = options.instance || null;
  55377. var invertUV = options.invertUV || false;
  55378. 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);
  55379. };
  55380. /**
  55381. * Creates an custom extruded shape mesh.
  55382. * 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.
  55383. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55384. *
  55385. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55386. * 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
  55387. * extruded along the Z axis.
  55388. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55389. * 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
  55390. * and the distance of this point from the begining of the path :
  55391. * ```javascript
  55392. * var rotationFunction = function(i, distance) {
  55393. * // do things
  55394. * return rotationValue; }
  55395. * ```
  55396. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55397. * 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
  55398. * and the distance of this point from the begining of the path :
  55399. * ```javascript
  55400. * var scaleFunction = function(i, distance) {
  55401. * // do things
  55402. * return scaleValue;}
  55403. * ```
  55404. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55405. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55406. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55407. * 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
  55408. * 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
  55409. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55411. * 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).
  55412. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55413. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55415. */
  55416. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55417. var path = options.path;
  55418. var shape = options.shape;
  55419. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55420. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55421. var ribbonCloseArray = options.ribbonCloseArray || false;
  55422. var ribbonClosePath = options.ribbonClosePath || false;
  55423. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55424. var updatable = options.updatable;
  55425. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55426. var instance = options.instance;
  55427. var invertUV = options.invertUV || false;
  55428. 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);
  55429. };
  55430. /**
  55431. * Creates lathe mesh.
  55432. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55433. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55434. *
  55435. * 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
  55436. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55437. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55438. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55439. * 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.
  55440. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55441. * 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
  55442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55443. * 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).
  55444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55445. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55447. */
  55448. MeshBuilder.CreateLathe = function (name, options, scene) {
  55449. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55450. var closed = (options.closed === undefined) ? true : options.closed;
  55451. var shape = options.shape;
  55452. var radius = options.radius || 1;
  55453. var tessellation = options.tessellation || 64;
  55454. var updatable = options.updatable;
  55455. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55456. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55457. var pi2 = Math.PI * 2;
  55458. var paths = new Array();
  55459. var invertUV = options.invertUV || false;
  55460. var i = 0;
  55461. var p = 0;
  55462. var step = pi2 / tessellation * arc;
  55463. var rotated;
  55464. var path = new Array();
  55465. ;
  55466. for (i = 0; i <= tessellation; i++) {
  55467. var path = [];
  55468. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55469. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55470. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55471. }
  55472. for (p = 0; p < shape.length; p++) {
  55473. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55474. path.push(rotated);
  55475. }
  55476. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55477. 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));
  55478. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55479. }
  55480. paths.push(path);
  55481. }
  55482. // lathe ribbon
  55483. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55484. return lathe;
  55485. };
  55486. /**
  55487. * Creates a plane mesh.
  55488. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55489. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55490. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55491. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55493. * 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).
  55494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55496. */
  55497. MeshBuilder.CreatePlane = function (name, options, scene) {
  55498. var plane = new BABYLON.Mesh(name, scene);
  55499. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55500. plane._originalBuilderSideOrientation = options.sideOrientation;
  55501. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55502. vertexData.applyToMesh(plane, options.updatable);
  55503. if (options.sourcePlane) {
  55504. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55505. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55506. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55507. plane.rotate(vectorProduct, product);
  55508. }
  55509. return plane;
  55510. };
  55511. /**
  55512. * Creates a ground mesh.
  55513. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55514. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55515. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55517. */
  55518. MeshBuilder.CreateGround = function (name, options, scene) {
  55519. var ground = new BABYLON.GroundMesh(name, scene);
  55520. ground._setReady(false);
  55521. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55522. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55523. ground._width = options.width || 1;
  55524. ground._height = options.height || 1;
  55525. ground._maxX = ground._width / 2;
  55526. ground._maxZ = ground._height / 2;
  55527. ground._minX = -ground._maxX;
  55528. ground._minZ = -ground._maxZ;
  55529. var vertexData = BABYLON.VertexData.CreateGround(options);
  55530. vertexData.applyToMesh(ground, options.updatable);
  55531. ground._setReady(true);
  55532. return ground;
  55533. };
  55534. /**
  55535. * Creates a tiled ground mesh.
  55536. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55537. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55538. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55539. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55540. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55541. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55542. * numbers of subdivisions on the ground width and height of each tile.
  55543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55544. */
  55545. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55546. var tiledGround = new BABYLON.Mesh(name, scene);
  55547. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55548. vertexData.applyToMesh(tiledGround, options.updatable);
  55549. return tiledGround;
  55550. };
  55551. /**
  55552. * Creates a ground mesh from a height map.
  55553. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55554. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55555. * The parameter `url` sets the URL of the height map image resource.
  55556. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55557. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55558. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55559. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55560. * 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.
  55561. * 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).
  55562. * This function is passed the newly built mesh :
  55563. * ```javascript
  55564. * function(mesh) { // do things
  55565. * return; }
  55566. * ```
  55567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55568. */
  55569. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55570. var width = options.width || 10.0;
  55571. var height = options.height || 10.0;
  55572. var subdivisions = options.subdivisions || 1 | 0;
  55573. var minHeight = options.minHeight || 0.0;
  55574. var maxHeight = options.maxHeight || 1.0;
  55575. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55576. var updatable = options.updatable;
  55577. var onReady = options.onReady;
  55578. var ground = new BABYLON.GroundMesh(name, scene);
  55579. ground._subdivisionsX = subdivisions;
  55580. ground._subdivisionsY = subdivisions;
  55581. ground._width = width;
  55582. ground._height = height;
  55583. ground._maxX = ground._width / 2.0;
  55584. ground._maxZ = ground._height / 2.0;
  55585. ground._minX = -ground._maxX;
  55586. ground._minZ = -ground._maxZ;
  55587. ground._setReady(false);
  55588. var onload = function (img) {
  55589. // Getting height map data
  55590. var canvas = document.createElement("canvas");
  55591. var context = canvas.getContext("2d");
  55592. if (!context) {
  55593. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55594. }
  55595. if (scene.isDisposed) {
  55596. return;
  55597. }
  55598. var bufferWidth = img.width;
  55599. var bufferHeight = img.height;
  55600. canvas.width = bufferWidth;
  55601. canvas.height = bufferHeight;
  55602. context.drawImage(img, 0, 0);
  55603. // Create VertexData from map data
  55604. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55605. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55606. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55607. width: width, height: height,
  55608. subdivisions: subdivisions,
  55609. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55610. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55611. });
  55612. vertexData.applyToMesh(ground, updatable);
  55613. ground._setReady(true);
  55614. //execute ready callback, if set
  55615. if (onReady) {
  55616. onReady(ground);
  55617. }
  55618. };
  55619. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55620. return ground;
  55621. };
  55622. /**
  55623. * Creates a polygon mesh.
  55624. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55625. * 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.
  55626. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55628. * 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).
  55629. * Remember you can only change the shape positions, not their number when updating a polygon.
  55630. */
  55631. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55632. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55633. var shape = options.shape;
  55634. var holes = options.holes || [];
  55635. var depth = options.depth || 0;
  55636. var contours = [];
  55637. var hole = [];
  55638. for (var i = 0; i < shape.length; i++) {
  55639. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55640. }
  55641. var epsilon = 0.00000001;
  55642. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55643. contours.pop();
  55644. }
  55645. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55646. for (var hNb = 0; hNb < holes.length; hNb++) {
  55647. hole = [];
  55648. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55649. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55650. }
  55651. polygonTriangulation.addHole(hole);
  55652. }
  55653. var polygon = polygonTriangulation.build(options.updatable, depth);
  55654. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55655. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55656. vertexData.applyToMesh(polygon, options.updatable);
  55657. return polygon;
  55658. };
  55659. ;
  55660. /**
  55661. * Creates an extruded polygon mesh, with depth in the Y direction.
  55662. * 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).
  55663. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55664. */
  55665. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55666. return MeshBuilder.CreatePolygon(name, options, scene);
  55667. };
  55668. ;
  55669. /**
  55670. * Creates a tube mesh.
  55671. * 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.
  55672. *
  55673. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55674. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55675. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55676. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55677. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55678. * 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.
  55679. * It must return a radius value (positive float) :
  55680. * ```javascript
  55681. * var radiusFunction = function(i, distance) {
  55682. * // do things
  55683. * return radius; }
  55684. * ```
  55685. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55686. * 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
  55687. * 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
  55688. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55689. * 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).
  55690. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55691. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55693. */
  55694. MeshBuilder.CreateTube = function (name, options, scene) {
  55695. var path = options.path;
  55696. var instance = options.instance;
  55697. var radius = 1.0;
  55698. if (instance) {
  55699. radius = instance.radius;
  55700. }
  55701. if (options.radius !== undefined) {
  55702. radius = options.radius;
  55703. }
  55704. ;
  55705. var tessellation = options.tessellation || 64 | 0;
  55706. var radiusFunction = options.radiusFunction || null;
  55707. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55708. var invertUV = options.invertUV || false;
  55709. var updatable = options.updatable;
  55710. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55711. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55712. // tube geometry
  55713. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55714. var tangents = path3D.getTangents();
  55715. var normals = path3D.getNormals();
  55716. var distances = path3D.getDistances();
  55717. var pi2 = Math.PI * 2;
  55718. var step = pi2 / tessellation * arc;
  55719. var returnRadius = function () { return radius; };
  55720. var radiusFunctionFinal = radiusFunction || returnRadius;
  55721. var circlePath;
  55722. var rad;
  55723. var normal;
  55724. var rotated;
  55725. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55726. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55727. for (var i = 0; i < path.length; i++) {
  55728. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55729. circlePath = Array(); // current circle array
  55730. normal = normals[i]; // current normal
  55731. for (var t = 0; t < tessellation; t++) {
  55732. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55733. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55734. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55735. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55736. circlePath[t] = rotated;
  55737. }
  55738. circlePaths[index] = circlePath;
  55739. index++;
  55740. }
  55741. // cap
  55742. var capPath = function (nbPoints, pathIndex) {
  55743. var pointCap = Array();
  55744. for (var i = 0; i < nbPoints; i++) {
  55745. pointCap.push(path[pathIndex]);
  55746. }
  55747. return pointCap;
  55748. };
  55749. switch (cap) {
  55750. case BABYLON.Mesh.NO_CAP:
  55751. break;
  55752. case BABYLON.Mesh.CAP_START:
  55753. circlePaths[0] = capPath(tessellation, 0);
  55754. circlePaths[1] = circlePaths[2].slice(0);
  55755. break;
  55756. case BABYLON.Mesh.CAP_END:
  55757. circlePaths[index] = circlePaths[index - 1].slice(0);
  55758. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55759. break;
  55760. case BABYLON.Mesh.CAP_ALL:
  55761. circlePaths[0] = capPath(tessellation, 0);
  55762. circlePaths[1] = circlePaths[2].slice(0);
  55763. circlePaths[index] = circlePaths[index - 1].slice(0);
  55764. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55765. break;
  55766. default:
  55767. break;
  55768. }
  55769. return circlePaths;
  55770. };
  55771. var path3D;
  55772. var pathArray;
  55773. if (instance) {
  55774. var arc = options.arc || instance.arc;
  55775. path3D = (instance.path3D).update(path);
  55776. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55777. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55778. instance.path3D = path3D;
  55779. instance.pathArray = pathArray;
  55780. instance.arc = arc;
  55781. instance.radius = radius;
  55782. return instance;
  55783. }
  55784. // tube creation
  55785. path3D = new BABYLON.Path3D(path);
  55786. var newPathArray = new Array();
  55787. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55788. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55789. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55790. tube.pathArray = pathArray;
  55791. tube.path3D = path3D;
  55792. tube.tessellation = tessellation;
  55793. tube.cap = cap;
  55794. tube.arc = options.arc;
  55795. tube.radius = radius;
  55796. return tube;
  55797. };
  55798. /**
  55799. * Creates a polyhedron mesh.
  55800. *
  55801. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55802. * 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
  55803. * to choose the wanted type.
  55804. * The parameter `size` (positive float, default 1) sets the polygon size.
  55805. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55806. * 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`.
  55807. * 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
  55808. * 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)`).
  55809. * 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
  55810. * 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.
  55811. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55812. * 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).
  55813. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55814. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55815. */
  55816. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55817. var polyhedron = new BABYLON.Mesh(name, scene);
  55818. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55819. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55820. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55821. vertexData.applyToMesh(polyhedron, options.updatable);
  55822. return polyhedron;
  55823. };
  55824. /**
  55825. * Creates a decal mesh.
  55826. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55827. * 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.
  55828. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55829. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55830. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55831. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55832. */
  55833. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55834. var indices = sourceMesh.getIndices();
  55835. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55836. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55837. var position = options.position || BABYLON.Vector3.Zero();
  55838. var normal = options.normal || BABYLON.Vector3.Up();
  55839. var size = options.size || BABYLON.Vector3.One();
  55840. var angle = options.angle || 0;
  55841. // Getting correct rotation
  55842. if (!normal) {
  55843. var target = new BABYLON.Vector3(0, 0, 1);
  55844. var camera = sourceMesh.getScene().activeCamera;
  55845. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55846. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55847. }
  55848. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55849. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55850. var pitch = Math.atan2(normal.y, len);
  55851. // Matrix
  55852. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55853. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55854. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55855. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55856. var vertexData = new BABYLON.VertexData();
  55857. vertexData.indices = [];
  55858. vertexData.positions = [];
  55859. vertexData.normals = [];
  55860. vertexData.uvs = [];
  55861. var currentVertexDataIndex = 0;
  55862. var extractDecalVector3 = function (indexId) {
  55863. var result = new BABYLON.PositionNormalVertex();
  55864. if (!indices || !positions || !normals) {
  55865. return result;
  55866. }
  55867. var vertexId = indices[indexId];
  55868. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55869. // Send vector to decal local world
  55870. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55871. // Get normal
  55872. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55873. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55874. return result;
  55875. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55876. var clip = function (vertices, axis) {
  55877. if (vertices.length === 0) {
  55878. return vertices;
  55879. }
  55880. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55881. var clipVertices = function (v0, v1) {
  55882. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55883. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55884. };
  55885. var result = new Array();
  55886. for (var index = 0; index < vertices.length; index += 3) {
  55887. var v1Out;
  55888. var v2Out;
  55889. var v3Out;
  55890. var total = 0;
  55891. var nV1 = null;
  55892. var nV2 = null;
  55893. var nV3 = null;
  55894. var nV4 = null;
  55895. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55896. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55897. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55898. v1Out = d1 > 0;
  55899. v2Out = d2 > 0;
  55900. v3Out = d3 > 0;
  55901. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55902. switch (total) {
  55903. case 0:
  55904. result.push(vertices[index]);
  55905. result.push(vertices[index + 1]);
  55906. result.push(vertices[index + 2]);
  55907. break;
  55908. case 1:
  55909. if (v1Out) {
  55910. nV1 = vertices[index + 1];
  55911. nV2 = vertices[index + 2];
  55912. nV3 = clipVertices(vertices[index], nV1);
  55913. nV4 = clipVertices(vertices[index], nV2);
  55914. }
  55915. if (v2Out) {
  55916. nV1 = vertices[index];
  55917. nV2 = vertices[index + 2];
  55918. nV3 = clipVertices(vertices[index + 1], nV1);
  55919. nV4 = clipVertices(vertices[index + 1], nV2);
  55920. result.push(nV3);
  55921. result.push(nV2.clone());
  55922. result.push(nV1.clone());
  55923. result.push(nV2.clone());
  55924. result.push(nV3.clone());
  55925. result.push(nV4);
  55926. break;
  55927. }
  55928. if (v3Out) {
  55929. nV1 = vertices[index];
  55930. nV2 = vertices[index + 1];
  55931. nV3 = clipVertices(vertices[index + 2], nV1);
  55932. nV4 = clipVertices(vertices[index + 2], nV2);
  55933. }
  55934. if (nV1 && nV2 && nV3 && nV4) {
  55935. result.push(nV1.clone());
  55936. result.push(nV2.clone());
  55937. result.push(nV3);
  55938. result.push(nV4);
  55939. result.push(nV3.clone());
  55940. result.push(nV2.clone());
  55941. }
  55942. break;
  55943. case 2:
  55944. if (!v1Out) {
  55945. nV1 = vertices[index].clone();
  55946. nV2 = clipVertices(nV1, vertices[index + 1]);
  55947. nV3 = clipVertices(nV1, vertices[index + 2]);
  55948. result.push(nV1);
  55949. result.push(nV2);
  55950. result.push(nV3);
  55951. }
  55952. if (!v2Out) {
  55953. nV1 = vertices[index + 1].clone();
  55954. nV2 = clipVertices(nV1, vertices[index + 2]);
  55955. nV3 = clipVertices(nV1, vertices[index]);
  55956. result.push(nV1);
  55957. result.push(nV2);
  55958. result.push(nV3);
  55959. }
  55960. if (!v3Out) {
  55961. nV1 = vertices[index + 2].clone();
  55962. nV2 = clipVertices(nV1, vertices[index]);
  55963. nV3 = clipVertices(nV1, vertices[index + 1]);
  55964. result.push(nV1);
  55965. result.push(nV2);
  55966. result.push(nV3);
  55967. }
  55968. break;
  55969. case 3:
  55970. break;
  55971. }
  55972. }
  55973. return result;
  55974. };
  55975. for (var index = 0; index < indices.length; index += 3) {
  55976. var faceVertices = new Array();
  55977. faceVertices.push(extractDecalVector3(index));
  55978. faceVertices.push(extractDecalVector3(index + 1));
  55979. faceVertices.push(extractDecalVector3(index + 2));
  55980. // Clip
  55981. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55982. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55983. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55984. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55985. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55986. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55987. if (faceVertices.length === 0) {
  55988. continue;
  55989. }
  55990. // Add UVs and get back to world
  55991. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55992. var vertex = faceVertices[vIndex];
  55993. //TODO check for Int32Array | Uint32Array | Uint16Array
  55994. vertexData.indices.push(currentVertexDataIndex);
  55995. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55996. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55997. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55998. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55999. currentVertexDataIndex++;
  56000. }
  56001. }
  56002. // Return mesh
  56003. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56004. vertexData.applyToMesh(decal);
  56005. decal.position = position.clone();
  56006. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56007. return decal;
  56008. };
  56009. // Privates
  56010. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56011. // extrusion geometry
  56012. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56013. var tangents = path3D.getTangents();
  56014. var normals = path3D.getNormals();
  56015. var binormals = path3D.getBinormals();
  56016. var distances = path3D.getDistances();
  56017. var angle = 0;
  56018. var returnScale = function () { return scale !== null ? scale : 1; };
  56019. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56020. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56021. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56022. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56023. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56024. for (var i = 0; i < curve.length; i++) {
  56025. var shapePath = new Array();
  56026. var angleStep = rotate(i, distances[i]);
  56027. var scaleRatio = scl(i, distances[i]);
  56028. for (var p = 0; p < shape.length; p++) {
  56029. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56030. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56031. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56032. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56033. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56034. shapePath[p] = rotated;
  56035. }
  56036. shapePaths[index] = shapePath;
  56037. angle += angleStep;
  56038. index++;
  56039. }
  56040. // cap
  56041. var capPath = function (shapePath) {
  56042. var pointCap = Array();
  56043. var barycenter = BABYLON.Vector3.Zero();
  56044. var i;
  56045. for (i = 0; i < shapePath.length; i++) {
  56046. barycenter.addInPlace(shapePath[i]);
  56047. }
  56048. barycenter.scaleInPlace(1.0 / shapePath.length);
  56049. for (i = 0; i < shapePath.length; i++) {
  56050. pointCap.push(barycenter);
  56051. }
  56052. return pointCap;
  56053. };
  56054. switch (cap) {
  56055. case BABYLON.Mesh.NO_CAP:
  56056. break;
  56057. case BABYLON.Mesh.CAP_START:
  56058. shapePaths[0] = capPath(shapePaths[2]);
  56059. shapePaths[1] = shapePaths[2];
  56060. break;
  56061. case BABYLON.Mesh.CAP_END:
  56062. shapePaths[index] = shapePaths[index - 1];
  56063. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56064. break;
  56065. case BABYLON.Mesh.CAP_ALL:
  56066. shapePaths[0] = capPath(shapePaths[2]);
  56067. shapePaths[1] = shapePaths[2];
  56068. shapePaths[index] = shapePaths[index - 1];
  56069. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56070. break;
  56071. default:
  56072. break;
  56073. }
  56074. return shapePaths;
  56075. };
  56076. var path3D;
  56077. var pathArray;
  56078. if (instance) {
  56079. path3D = (instance.path3D).update(curve);
  56080. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56081. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56082. return instance;
  56083. }
  56084. // extruded shape creation
  56085. path3D = new BABYLON.Path3D(curve);
  56086. var newShapePaths = new Array();
  56087. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56088. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56089. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56090. extrudedGeneric.pathArray = pathArray;
  56091. extrudedGeneric.path3D = path3D;
  56092. extrudedGeneric.cap = cap;
  56093. return extrudedGeneric;
  56094. };
  56095. return MeshBuilder;
  56096. }());
  56097. BABYLON.MeshBuilder = MeshBuilder;
  56098. })(BABYLON || (BABYLON = {}));
  56099. //# sourceMappingURL=babylon.meshBuilder.js.map
  56100. var BABYLON;
  56101. (function (BABYLON) {
  56102. /**
  56103. * Draco compression (https://google.github.io/draco/)
  56104. */
  56105. var DracoCompression = /** @class */ (function () {
  56106. /**
  56107. * Constructor
  56108. * @param numWorkers The number of workers for async operations
  56109. */
  56110. function DracoCompression(numWorkers) {
  56111. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56112. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56113. if (!workerBlobUrl || !Worker) {
  56114. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56115. return;
  56116. }
  56117. var workers = new Array(numWorkers);
  56118. for (var i = 0; i < workers.length; i++) {
  56119. var worker = new Worker(workerBlobUrl);
  56120. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56121. workers[i] = worker;
  56122. }
  56123. this._workerPool = new BABYLON.WorkerPool(workers);
  56124. }
  56125. /**
  56126. * Stop all async operations and release resources.
  56127. */
  56128. DracoCompression.prototype.dispose = function () {
  56129. this._workerPool.dispose();
  56130. delete this._workerPool;
  56131. };
  56132. /**
  56133. * Decode Draco compressed mesh data to vertex data.
  56134. * @param data The array buffer view for the Draco compression data
  56135. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56136. * @returns A promise that resolves with the decoded vertex data
  56137. */
  56138. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56139. var _this = this;
  56140. return new Promise(function (resolve, reject) {
  56141. _this._workerPool.push(function (worker, onComplete) {
  56142. var vertexData = new BABYLON.VertexData();
  56143. var onError = function (error) {
  56144. worker.removeEventListener("error", onError);
  56145. worker.removeEventListener("message", onMessage);
  56146. reject(error);
  56147. onComplete();
  56148. };
  56149. var onMessage = function (message) {
  56150. if (message.data === "done") {
  56151. worker.removeEventListener("error", onError);
  56152. worker.removeEventListener("message", onMessage);
  56153. resolve(vertexData);
  56154. onComplete();
  56155. }
  56156. else if (message.data.id === "indices") {
  56157. vertexData.indices = message.data.value;
  56158. }
  56159. else {
  56160. vertexData.set(message.data.value, message.data.id);
  56161. }
  56162. };
  56163. worker.addEventListener("error", onError);
  56164. worker.addEventListener("message", onMessage);
  56165. var dataCopy = new Uint8Array(data.byteLength);
  56166. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56167. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56168. });
  56169. });
  56170. };
  56171. /**
  56172. * The worker function that gets converted to a blob url to pass into a worker.
  56173. */
  56174. DracoCompression._Worker = function () {
  56175. // self is actually a DedicatedWorkerGlobalScope
  56176. var _self = self;
  56177. var decodeMesh = function (data, attributes) {
  56178. var dracoModule = new DracoDecoderModule();
  56179. var buffer = new dracoModule.DecoderBuffer();
  56180. buffer.Init(data, data.byteLength);
  56181. var decoder = new dracoModule.Decoder();
  56182. var geometry;
  56183. var status;
  56184. try {
  56185. var type = decoder.GetEncodedGeometryType(buffer);
  56186. switch (type) {
  56187. case dracoModule.TRIANGULAR_MESH:
  56188. geometry = new dracoModule.Mesh();
  56189. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56190. break;
  56191. case dracoModule.POINT_CLOUD:
  56192. geometry = new dracoModule.PointCloud();
  56193. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56194. break;
  56195. default:
  56196. throw new Error("Invalid geometry type " + type);
  56197. }
  56198. if (!status.ok() || !geometry.ptr) {
  56199. throw new Error(status.error_msg());
  56200. }
  56201. var numPoints = geometry.num_points();
  56202. if (type === dracoModule.TRIANGULAR_MESH) {
  56203. var numFaces = geometry.num_faces();
  56204. var faceIndices = new dracoModule.DracoInt32Array();
  56205. try {
  56206. var indices = new Uint32Array(numFaces * 3);
  56207. for (var i = 0; i < numFaces; i++) {
  56208. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56209. var offset = i * 3;
  56210. indices[offset + 0] = faceIndices.GetValue(0);
  56211. indices[offset + 1] = faceIndices.GetValue(1);
  56212. indices[offset + 2] = faceIndices.GetValue(2);
  56213. }
  56214. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56215. }
  56216. finally {
  56217. dracoModule.destroy(faceIndices);
  56218. }
  56219. }
  56220. for (var kind in attributes) {
  56221. var uniqueId = attributes[kind];
  56222. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56223. var dracoData = new dracoModule.DracoFloat32Array();
  56224. try {
  56225. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56226. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56227. for (var i = 0; i < babylonData.length; i++) {
  56228. babylonData[i] = dracoData.GetValue(i);
  56229. }
  56230. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56231. }
  56232. finally {
  56233. dracoModule.destroy(dracoData);
  56234. }
  56235. }
  56236. }
  56237. finally {
  56238. if (geometry) {
  56239. dracoModule.destroy(geometry);
  56240. }
  56241. dracoModule.destroy(decoder);
  56242. dracoModule.destroy(buffer);
  56243. }
  56244. _self.postMessage("done");
  56245. };
  56246. _self.onmessage = function (event) {
  56247. switch (event.data.id) {
  56248. case "initDecoder": {
  56249. importScripts(event.data.url);
  56250. break;
  56251. }
  56252. case "decodeMesh": {
  56253. decodeMesh(event.data.data, event.data.attributes);
  56254. break;
  56255. }
  56256. }
  56257. };
  56258. };
  56259. DracoCompression._GetDefaultDecoderUrl = function () {
  56260. if (!BABYLON.Tools.IsWindowObjectExist) {
  56261. return null;
  56262. }
  56263. for (var i = 0; i < document.scripts.length; i++) {
  56264. if (document.scripts[i].type === "text/x-draco-decoder") {
  56265. return document.scripts[i].src;
  56266. }
  56267. }
  56268. return null;
  56269. };
  56270. /**
  56271. * Gets the url to the draco decoder if available.
  56272. */
  56273. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56274. return DracoCompression;
  56275. }());
  56276. BABYLON.DracoCompression = DracoCompression;
  56277. })(BABYLON || (BABYLON = {}));
  56278. //# sourceMappingURL=babylon.dracoCompression.js.map
  56279. var BABYLON;
  56280. (function (BABYLON) {
  56281. var AudioEngine = /** @class */ (function () {
  56282. function AudioEngine() {
  56283. this._audioContext = null;
  56284. this._audioContextInitialized = false;
  56285. this.canUseWebAudio = false;
  56286. this.WarnedWebAudioUnsupported = false;
  56287. this.unlocked = false;
  56288. this.isMP3supported = false;
  56289. this.isOGGsupported = false;
  56290. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56291. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56292. this.canUseWebAudio = true;
  56293. }
  56294. var audioElem = document.createElement('audio');
  56295. try {
  56296. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56297. this.isMP3supported = true;
  56298. }
  56299. }
  56300. catch (e) {
  56301. // protect error during capability check.
  56302. }
  56303. try {
  56304. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56305. this.isOGGsupported = true;
  56306. }
  56307. }
  56308. catch (e) {
  56309. // protect error during capability check.
  56310. }
  56311. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56312. this._unlockiOSaudio();
  56313. }
  56314. else {
  56315. this.unlocked = true;
  56316. }
  56317. }
  56318. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56319. get: function () {
  56320. if (!this._audioContextInitialized) {
  56321. this._initializeAudioContext();
  56322. }
  56323. return this._audioContext;
  56324. },
  56325. enumerable: true,
  56326. configurable: true
  56327. });
  56328. AudioEngine.prototype._unlockiOSaudio = function () {
  56329. var _this = this;
  56330. var unlockaudio = function () {
  56331. if (!_this.audioContext) {
  56332. return;
  56333. }
  56334. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56335. var source = _this.audioContext.createBufferSource();
  56336. source.buffer = buffer;
  56337. source.connect(_this.audioContext.destination);
  56338. source.start(0);
  56339. setTimeout(function () {
  56340. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56341. _this.unlocked = true;
  56342. window.removeEventListener('touchend', unlockaudio, false);
  56343. if (_this.onAudioUnlocked) {
  56344. _this.onAudioUnlocked();
  56345. }
  56346. }
  56347. }, 0);
  56348. };
  56349. window.addEventListener('touchend', unlockaudio, false);
  56350. };
  56351. AudioEngine.prototype._initializeAudioContext = function () {
  56352. try {
  56353. if (this.canUseWebAudio) {
  56354. this._audioContext = new AudioContext();
  56355. // create a global volume gain node
  56356. this.masterGain = this._audioContext.createGain();
  56357. this.masterGain.gain.value = 1;
  56358. this.masterGain.connect(this._audioContext.destination);
  56359. this._audioContextInitialized = true;
  56360. }
  56361. }
  56362. catch (e) {
  56363. this.canUseWebAudio = false;
  56364. BABYLON.Tools.Error("Web Audio: " + e.message);
  56365. }
  56366. };
  56367. AudioEngine.prototype.dispose = function () {
  56368. if (this.canUseWebAudio && this._audioContextInitialized) {
  56369. if (this._connectedAnalyser && this._audioContext) {
  56370. this._connectedAnalyser.stopDebugCanvas();
  56371. this._connectedAnalyser.dispose();
  56372. this.masterGain.disconnect();
  56373. this.masterGain.connect(this._audioContext.destination);
  56374. this._connectedAnalyser = null;
  56375. }
  56376. this.masterGain.gain.value = 1;
  56377. }
  56378. this.WarnedWebAudioUnsupported = false;
  56379. };
  56380. AudioEngine.prototype.getGlobalVolume = function () {
  56381. if (this.canUseWebAudio && this._audioContextInitialized) {
  56382. return this.masterGain.gain.value;
  56383. }
  56384. else {
  56385. return -1;
  56386. }
  56387. };
  56388. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56389. if (this.canUseWebAudio && this._audioContextInitialized) {
  56390. this.masterGain.gain.value = newVolume;
  56391. }
  56392. };
  56393. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56394. if (this._connectedAnalyser) {
  56395. this._connectedAnalyser.stopDebugCanvas();
  56396. }
  56397. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56398. this._connectedAnalyser = analyser;
  56399. this.masterGain.disconnect();
  56400. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56401. }
  56402. };
  56403. return AudioEngine;
  56404. }());
  56405. BABYLON.AudioEngine = AudioEngine;
  56406. })(BABYLON || (BABYLON = {}));
  56407. //# sourceMappingURL=babylon.audioEngine.js.map
  56408. var BABYLON;
  56409. (function (BABYLON) {
  56410. var Sound = /** @class */ (function () {
  56411. /**
  56412. * Create a sound and attach it to a scene
  56413. * @param name Name of your sound
  56414. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56415. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56416. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56417. */
  56418. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56419. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56420. var _this = this;
  56421. this.autoplay = false;
  56422. this.loop = false;
  56423. this.useCustomAttenuation = false;
  56424. this.spatialSound = false;
  56425. this.refDistance = 1;
  56426. this.rolloffFactor = 1;
  56427. this.maxDistance = 100;
  56428. this.distanceModel = "linear";
  56429. this._panningModel = "equalpower";
  56430. this._playbackRate = 1;
  56431. this._streaming = false;
  56432. this._startTime = 0;
  56433. this._startOffset = 0;
  56434. this._position = BABYLON.Vector3.Zero();
  56435. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56436. this._volume = 1;
  56437. this._isReadyToPlay = false;
  56438. this.isPlaying = false;
  56439. this.isPaused = false;
  56440. this._isDirectional = false;
  56441. // Used if you'd like to create a directional sound.
  56442. // If not set, the sound will be omnidirectional
  56443. this._coneInnerAngle = 360;
  56444. this._coneOuterAngle = 360;
  56445. this._coneOuterGain = 0;
  56446. this._isOutputConnected = false;
  56447. this._urlType = "Unknown";
  56448. this.name = name;
  56449. this._scene = scene;
  56450. this._readyToPlayCallback = readyToPlayCallback;
  56451. // Default custom attenuation function is a linear attenuation
  56452. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56453. if (currentDistance < maxDistance) {
  56454. return currentVolume * (1 - currentDistance / maxDistance);
  56455. }
  56456. else {
  56457. return 0;
  56458. }
  56459. };
  56460. if (options) {
  56461. this.autoplay = options.autoplay || false;
  56462. this.loop = options.loop || false;
  56463. // if volume === 0, we need another way to check this option
  56464. if (options.volume !== undefined) {
  56465. this._volume = options.volume;
  56466. }
  56467. this.spatialSound = options.spatialSound || false;
  56468. this.maxDistance = options.maxDistance || 100;
  56469. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56470. this.rolloffFactor = options.rolloffFactor || 1;
  56471. this.refDistance = options.refDistance || 1;
  56472. this.distanceModel = options.distanceModel || "linear";
  56473. this._playbackRate = options.playbackRate || 1;
  56474. this._streaming = options.streaming || false;
  56475. }
  56476. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56477. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56478. this._soundGain.gain.value = this._volume;
  56479. this._inputAudioNode = this._soundGain;
  56480. this._ouputAudioNode = this._soundGain;
  56481. if (this.spatialSound) {
  56482. this._createSpatialParameters();
  56483. }
  56484. this._scene.mainSoundTrack.AddSound(this);
  56485. var validParameter = true;
  56486. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56487. if (urlOrArrayBuffer) {
  56488. if (typeof (urlOrArrayBuffer) === "string")
  56489. this._urlType = "String";
  56490. if (Array.isArray(urlOrArrayBuffer))
  56491. this._urlType = "Array";
  56492. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56493. this._urlType = "ArrayBuffer";
  56494. var urls = [];
  56495. var codecSupportedFound = false;
  56496. switch (this._urlType) {
  56497. case "ArrayBuffer":
  56498. if (urlOrArrayBuffer.byteLength > 0) {
  56499. codecSupportedFound = true;
  56500. this._soundLoaded(urlOrArrayBuffer);
  56501. }
  56502. break;
  56503. case "String":
  56504. urls.push(urlOrArrayBuffer);
  56505. case "Array":
  56506. if (urls.length === 0)
  56507. urls = urlOrArrayBuffer;
  56508. // If we found a supported format, we load it immediately and stop the loop
  56509. for (var i = 0; i < urls.length; i++) {
  56510. var url = urls[i];
  56511. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56512. codecSupportedFound = true;
  56513. }
  56514. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56515. codecSupportedFound = true;
  56516. }
  56517. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56518. codecSupportedFound = true;
  56519. }
  56520. if (url.indexOf("blob:") !== -1) {
  56521. codecSupportedFound = true;
  56522. }
  56523. if (codecSupportedFound) {
  56524. // Loading sound using XHR2
  56525. if (!this._streaming) {
  56526. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56527. }
  56528. else {
  56529. this._htmlAudioElement = new Audio(url);
  56530. this._htmlAudioElement.controls = false;
  56531. this._htmlAudioElement.loop = this.loop;
  56532. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56533. this._htmlAudioElement.preload = "auto";
  56534. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56535. _this._isReadyToPlay = true;
  56536. if (_this.autoplay) {
  56537. _this.play();
  56538. }
  56539. if (_this._readyToPlayCallback) {
  56540. _this._readyToPlayCallback();
  56541. }
  56542. });
  56543. document.body.appendChild(this._htmlAudioElement);
  56544. }
  56545. break;
  56546. }
  56547. }
  56548. break;
  56549. default:
  56550. validParameter = false;
  56551. break;
  56552. }
  56553. if (!validParameter) {
  56554. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56555. }
  56556. else {
  56557. if (!codecSupportedFound) {
  56558. this._isReadyToPlay = true;
  56559. // Simulating a ready to play event to avoid breaking code path
  56560. if (this._readyToPlayCallback) {
  56561. window.setTimeout(function () {
  56562. if (_this._readyToPlayCallback) {
  56563. _this._readyToPlayCallback();
  56564. }
  56565. }, 1000);
  56566. }
  56567. }
  56568. }
  56569. }
  56570. }
  56571. else {
  56572. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56573. this._scene.mainSoundTrack.AddSound(this);
  56574. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56575. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56576. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56577. }
  56578. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56579. if (this._readyToPlayCallback) {
  56580. window.setTimeout(function () {
  56581. if (_this._readyToPlayCallback) {
  56582. _this._readyToPlayCallback();
  56583. }
  56584. }, 1000);
  56585. }
  56586. }
  56587. }
  56588. Sound.prototype.dispose = function () {
  56589. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56590. if (this.isPlaying) {
  56591. this.stop();
  56592. }
  56593. this._isReadyToPlay = false;
  56594. if (this.soundTrackId === -1) {
  56595. this._scene.mainSoundTrack.RemoveSound(this);
  56596. }
  56597. else {
  56598. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56599. }
  56600. if (this._soundGain) {
  56601. this._soundGain.disconnect();
  56602. this._soundGain = null;
  56603. }
  56604. if (this._soundPanner) {
  56605. this._soundPanner.disconnect();
  56606. this._soundPanner = null;
  56607. }
  56608. if (this._soundSource) {
  56609. this._soundSource.disconnect();
  56610. this._soundSource = null;
  56611. }
  56612. this._audioBuffer = null;
  56613. if (this._htmlAudioElement) {
  56614. this._htmlAudioElement.pause();
  56615. this._htmlAudioElement.src = "";
  56616. document.body.removeChild(this._htmlAudioElement);
  56617. }
  56618. if (this._connectedMesh && this._registerFunc) {
  56619. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56620. this._connectedMesh = null;
  56621. }
  56622. }
  56623. };
  56624. Sound.prototype.isReady = function () {
  56625. return this._isReadyToPlay;
  56626. };
  56627. Sound.prototype._soundLoaded = function (audioData) {
  56628. var _this = this;
  56629. if (!BABYLON.Engine.audioEngine.audioContext) {
  56630. return;
  56631. }
  56632. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56633. _this._audioBuffer = buffer;
  56634. _this._isReadyToPlay = true;
  56635. if (_this.autoplay) {
  56636. _this.play();
  56637. }
  56638. if (_this._readyToPlayCallback) {
  56639. _this._readyToPlayCallback();
  56640. }
  56641. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56642. };
  56643. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56644. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56645. this._audioBuffer = audioBuffer;
  56646. this._isReadyToPlay = true;
  56647. }
  56648. };
  56649. Sound.prototype.updateOptions = function (options) {
  56650. if (options) {
  56651. this.loop = options.loop || this.loop;
  56652. this.maxDistance = options.maxDistance || this.maxDistance;
  56653. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56654. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56655. this.refDistance = options.refDistance || this.refDistance;
  56656. this.distanceModel = options.distanceModel || this.distanceModel;
  56657. this._playbackRate = options.playbackRate || this._playbackRate;
  56658. this._updateSpatialParameters();
  56659. if (this.isPlaying) {
  56660. if (this._streaming) {
  56661. this._htmlAudioElement.playbackRate = this._playbackRate;
  56662. }
  56663. else {
  56664. if (this._soundSource) {
  56665. this._soundSource.playbackRate.value = this._playbackRate;
  56666. }
  56667. }
  56668. }
  56669. }
  56670. };
  56671. Sound.prototype._createSpatialParameters = function () {
  56672. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56673. if (this._scene.headphone) {
  56674. this._panningModel = "HRTF";
  56675. }
  56676. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56677. this._updateSpatialParameters();
  56678. this._soundPanner.connect(this._ouputAudioNode);
  56679. this._inputAudioNode = this._soundPanner;
  56680. }
  56681. };
  56682. Sound.prototype._updateSpatialParameters = function () {
  56683. if (this.spatialSound && this._soundPanner) {
  56684. if (this.useCustomAttenuation) {
  56685. // Tricks to disable in a way embedded Web Audio attenuation
  56686. this._soundPanner.distanceModel = "linear";
  56687. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56688. this._soundPanner.refDistance = 1;
  56689. this._soundPanner.rolloffFactor = 1;
  56690. this._soundPanner.panningModel = this._panningModel;
  56691. }
  56692. else {
  56693. this._soundPanner.distanceModel = this.distanceModel;
  56694. this._soundPanner.maxDistance = this.maxDistance;
  56695. this._soundPanner.refDistance = this.refDistance;
  56696. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56697. this._soundPanner.panningModel = this._panningModel;
  56698. }
  56699. }
  56700. };
  56701. Sound.prototype.switchPanningModelToHRTF = function () {
  56702. this._panningModel = "HRTF";
  56703. this._switchPanningModel();
  56704. };
  56705. Sound.prototype.switchPanningModelToEqualPower = function () {
  56706. this._panningModel = "equalpower";
  56707. this._switchPanningModel();
  56708. };
  56709. Sound.prototype._switchPanningModel = function () {
  56710. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56711. this._soundPanner.panningModel = this._panningModel;
  56712. }
  56713. };
  56714. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56715. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56716. if (this._isOutputConnected) {
  56717. this._ouputAudioNode.disconnect();
  56718. }
  56719. this._ouputAudioNode.connect(soundTrackAudioNode);
  56720. this._isOutputConnected = true;
  56721. }
  56722. };
  56723. /**
  56724. * Transform this sound into a directional source
  56725. * @param coneInnerAngle Size of the inner cone in degree
  56726. * @param coneOuterAngle Size of the outer cone in degree
  56727. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56728. */
  56729. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56730. if (coneOuterAngle < coneInnerAngle) {
  56731. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56732. return;
  56733. }
  56734. this._coneInnerAngle = coneInnerAngle;
  56735. this._coneOuterAngle = coneOuterAngle;
  56736. this._coneOuterGain = coneOuterGain;
  56737. this._isDirectional = true;
  56738. if (this.isPlaying && this.loop) {
  56739. this.stop();
  56740. this.play();
  56741. }
  56742. };
  56743. Sound.prototype.setPosition = function (newPosition) {
  56744. this._position = newPosition;
  56745. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56746. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56747. }
  56748. };
  56749. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56750. this._localDirection = newLocalDirection;
  56751. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56752. this._updateDirection();
  56753. }
  56754. };
  56755. Sound.prototype._updateDirection = function () {
  56756. if (!this._connectedMesh || !this._soundPanner) {
  56757. return;
  56758. }
  56759. var mat = this._connectedMesh.getWorldMatrix();
  56760. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56761. direction.normalize();
  56762. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56763. };
  56764. Sound.prototype.updateDistanceFromListener = function () {
  56765. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56766. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56767. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56768. }
  56769. };
  56770. Sound.prototype.setAttenuationFunction = function (callback) {
  56771. this._customAttenuationFunction = callback;
  56772. };
  56773. /**
  56774. * Play the sound
  56775. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56776. * @param offset (optional) Start the sound setting it at a specific time
  56777. */
  56778. Sound.prototype.play = function (time, offset) {
  56779. var _this = this;
  56780. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56781. try {
  56782. if (this._startOffset < 0) {
  56783. time = -this._startOffset;
  56784. this._startOffset = 0;
  56785. }
  56786. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56787. if (!this._soundSource || !this._streamingSource) {
  56788. if (this.spatialSound && this._soundPanner) {
  56789. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56790. if (this._isDirectional) {
  56791. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56792. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56793. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56794. if (this._connectedMesh) {
  56795. this._updateDirection();
  56796. }
  56797. else {
  56798. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56799. }
  56800. }
  56801. }
  56802. }
  56803. if (this._streaming) {
  56804. if (!this._streamingSource) {
  56805. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56806. this._htmlAudioElement.onended = function () { _this._onended(); };
  56807. this._htmlAudioElement.playbackRate = this._playbackRate;
  56808. }
  56809. this._streamingSource.disconnect();
  56810. this._streamingSource.connect(this._inputAudioNode);
  56811. this._htmlAudioElement.play();
  56812. }
  56813. else {
  56814. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56815. this._soundSource.buffer = this._audioBuffer;
  56816. this._soundSource.connect(this._inputAudioNode);
  56817. this._soundSource.loop = this.loop;
  56818. this._soundSource.playbackRate.value = this._playbackRate;
  56819. this._soundSource.onended = function () { _this._onended(); };
  56820. if (this._soundSource.buffer) {
  56821. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56822. }
  56823. }
  56824. this._startTime = startTime;
  56825. this.isPlaying = true;
  56826. this.isPaused = false;
  56827. }
  56828. catch (ex) {
  56829. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56830. }
  56831. }
  56832. };
  56833. Sound.prototype._onended = function () {
  56834. this.isPlaying = false;
  56835. if (this.onended) {
  56836. this.onended();
  56837. }
  56838. };
  56839. /**
  56840. * Stop the sound
  56841. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56842. */
  56843. Sound.prototype.stop = function (time) {
  56844. if (this.isPlaying) {
  56845. if (this._streaming) {
  56846. this._htmlAudioElement.pause();
  56847. // Test needed for Firefox or it will generate an Invalid State Error
  56848. if (this._htmlAudioElement.currentTime > 0) {
  56849. this._htmlAudioElement.currentTime = 0;
  56850. }
  56851. }
  56852. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56853. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56854. this._soundSource.stop(stopTime);
  56855. this._soundSource.onended = function () { };
  56856. if (!this.isPaused) {
  56857. this._startOffset = 0;
  56858. }
  56859. }
  56860. this.isPlaying = false;
  56861. }
  56862. };
  56863. Sound.prototype.pause = function () {
  56864. if (this.isPlaying) {
  56865. this.isPaused = true;
  56866. if (this._streaming) {
  56867. this._htmlAudioElement.pause();
  56868. }
  56869. else if (BABYLON.Engine.audioEngine.audioContext) {
  56870. this.stop(0);
  56871. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56872. }
  56873. }
  56874. };
  56875. Sound.prototype.setVolume = function (newVolume, time) {
  56876. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56877. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56878. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56879. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56880. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56881. }
  56882. else {
  56883. this._soundGain.gain.value = newVolume;
  56884. }
  56885. }
  56886. this._volume = newVolume;
  56887. };
  56888. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56889. this._playbackRate = newPlaybackRate;
  56890. if (this.isPlaying) {
  56891. if (this._streaming) {
  56892. this._htmlAudioElement.playbackRate = this._playbackRate;
  56893. }
  56894. else if (this._soundSource) {
  56895. this._soundSource.playbackRate.value = this._playbackRate;
  56896. }
  56897. }
  56898. };
  56899. Sound.prototype.getVolume = function () {
  56900. return this._volume;
  56901. };
  56902. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56903. var _this = this;
  56904. if (this._connectedMesh && this._registerFunc) {
  56905. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56906. this._registerFunc = null;
  56907. }
  56908. this._connectedMesh = meshToConnectTo;
  56909. if (!this.spatialSound) {
  56910. this.spatialSound = true;
  56911. this._createSpatialParameters();
  56912. if (this.isPlaying && this.loop) {
  56913. this.stop();
  56914. this.play();
  56915. }
  56916. }
  56917. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56918. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56919. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56920. };
  56921. Sound.prototype.detachFromMesh = function () {
  56922. if (this._connectedMesh && this._registerFunc) {
  56923. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56924. this._registerFunc = null;
  56925. this._connectedMesh = null;
  56926. }
  56927. };
  56928. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56929. if (!node.getBoundingInfo) {
  56930. return;
  56931. }
  56932. var mesh = node;
  56933. var boundingInfo = mesh.getBoundingInfo();
  56934. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56935. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56936. this._updateDirection();
  56937. }
  56938. };
  56939. Sound.prototype.clone = function () {
  56940. var _this = this;
  56941. if (!this._streaming) {
  56942. var setBufferAndRun = function () {
  56943. if (_this._isReadyToPlay) {
  56944. clonedSound._audioBuffer = _this.getAudioBuffer();
  56945. clonedSound._isReadyToPlay = true;
  56946. if (clonedSound.autoplay) {
  56947. clonedSound.play();
  56948. }
  56949. }
  56950. else {
  56951. window.setTimeout(setBufferAndRun, 300);
  56952. }
  56953. };
  56954. var currentOptions = {
  56955. autoplay: this.autoplay, loop: this.loop,
  56956. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56957. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56958. refDistance: this.refDistance, distanceModel: this.distanceModel
  56959. };
  56960. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56961. if (this.useCustomAttenuation) {
  56962. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56963. }
  56964. clonedSound.setPosition(this._position);
  56965. clonedSound.setPlaybackRate(this._playbackRate);
  56966. setBufferAndRun();
  56967. return clonedSound;
  56968. }
  56969. else {
  56970. return null;
  56971. }
  56972. };
  56973. Sound.prototype.getAudioBuffer = function () {
  56974. return this._audioBuffer;
  56975. };
  56976. Sound.prototype.serialize = function () {
  56977. var serializationObject = {
  56978. name: this.name,
  56979. url: this.name,
  56980. autoplay: this.autoplay,
  56981. loop: this.loop,
  56982. volume: this._volume,
  56983. spatialSound: this.spatialSound,
  56984. maxDistance: this.maxDistance,
  56985. rolloffFactor: this.rolloffFactor,
  56986. refDistance: this.refDistance,
  56987. distanceModel: this.distanceModel,
  56988. playbackRate: this._playbackRate,
  56989. panningModel: this._panningModel,
  56990. soundTrackId: this.soundTrackId
  56991. };
  56992. if (this.spatialSound) {
  56993. if (this._connectedMesh)
  56994. serializationObject.connectedMeshId = this._connectedMesh.id;
  56995. serializationObject.position = this._position.asArray();
  56996. serializationObject.refDistance = this.refDistance;
  56997. serializationObject.distanceModel = this.distanceModel;
  56998. serializationObject.isDirectional = this._isDirectional;
  56999. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57000. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57001. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57002. serializationObject.coneOuterGain = this._coneOuterGain;
  57003. }
  57004. return serializationObject;
  57005. };
  57006. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57007. var soundName = parsedSound.name;
  57008. var soundUrl;
  57009. if (parsedSound.url) {
  57010. soundUrl = rootUrl + parsedSound.url;
  57011. }
  57012. else {
  57013. soundUrl = rootUrl + soundName;
  57014. }
  57015. var options = {
  57016. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57017. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57018. rolloffFactor: parsedSound.rolloffFactor,
  57019. refDistance: parsedSound.refDistance,
  57020. distanceModel: parsedSound.distanceModel,
  57021. playbackRate: parsedSound.playbackRate
  57022. };
  57023. var newSound;
  57024. if (!sourceSound) {
  57025. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57026. scene._addPendingData(newSound);
  57027. }
  57028. else {
  57029. var setBufferAndRun = function () {
  57030. if (sourceSound._isReadyToPlay) {
  57031. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57032. newSound._isReadyToPlay = true;
  57033. if (newSound.autoplay) {
  57034. newSound.play();
  57035. }
  57036. }
  57037. else {
  57038. window.setTimeout(setBufferAndRun, 300);
  57039. }
  57040. };
  57041. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57042. setBufferAndRun();
  57043. }
  57044. if (parsedSound.position) {
  57045. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57046. newSound.setPosition(soundPosition);
  57047. }
  57048. if (parsedSound.isDirectional) {
  57049. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57050. if (parsedSound.localDirectionToMesh) {
  57051. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57052. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57053. }
  57054. }
  57055. if (parsedSound.connectedMeshId) {
  57056. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57057. if (connectedMesh) {
  57058. newSound.attachToMesh(connectedMesh);
  57059. }
  57060. }
  57061. return newSound;
  57062. };
  57063. return Sound;
  57064. }());
  57065. BABYLON.Sound = Sound;
  57066. })(BABYLON || (BABYLON = {}));
  57067. //# sourceMappingURL=babylon.sound.js.map
  57068. var BABYLON;
  57069. (function (BABYLON) {
  57070. var SoundTrack = /** @class */ (function () {
  57071. function SoundTrack(scene, options) {
  57072. this.id = -1;
  57073. this._isMainTrack = false;
  57074. this._isInitialized = false;
  57075. this._scene = scene;
  57076. this.soundCollection = new Array();
  57077. this._options = options;
  57078. if (!this._isMainTrack) {
  57079. this._scene.soundTracks.push(this);
  57080. this.id = this._scene.soundTracks.length - 1;
  57081. }
  57082. }
  57083. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57084. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57085. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57086. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57087. if (this._options) {
  57088. if (this._options.volume) {
  57089. this._outputAudioNode.gain.value = this._options.volume;
  57090. }
  57091. if (this._options.mainTrack) {
  57092. this._isMainTrack = this._options.mainTrack;
  57093. }
  57094. }
  57095. this._isInitialized = true;
  57096. }
  57097. };
  57098. SoundTrack.prototype.dispose = function () {
  57099. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57100. if (this._connectedAnalyser) {
  57101. this._connectedAnalyser.stopDebugCanvas();
  57102. }
  57103. while (this.soundCollection.length) {
  57104. this.soundCollection[0].dispose();
  57105. }
  57106. if (this._outputAudioNode) {
  57107. this._outputAudioNode.disconnect();
  57108. }
  57109. this._outputAudioNode = null;
  57110. }
  57111. };
  57112. SoundTrack.prototype.AddSound = function (sound) {
  57113. if (!this._isInitialized) {
  57114. this._initializeSoundTrackAudioGraph();
  57115. }
  57116. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57117. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57118. }
  57119. if (sound.soundTrackId) {
  57120. if (sound.soundTrackId === -1) {
  57121. this._scene.mainSoundTrack.RemoveSound(sound);
  57122. }
  57123. else {
  57124. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57125. }
  57126. }
  57127. this.soundCollection.push(sound);
  57128. sound.soundTrackId = this.id;
  57129. };
  57130. SoundTrack.prototype.RemoveSound = function (sound) {
  57131. var index = this.soundCollection.indexOf(sound);
  57132. if (index !== -1) {
  57133. this.soundCollection.splice(index, 1);
  57134. }
  57135. };
  57136. SoundTrack.prototype.setVolume = function (newVolume) {
  57137. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57138. this._outputAudioNode.gain.value = newVolume;
  57139. }
  57140. };
  57141. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57142. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57143. for (var i = 0; i < this.soundCollection.length; i++) {
  57144. this.soundCollection[i].switchPanningModelToHRTF();
  57145. }
  57146. }
  57147. };
  57148. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57149. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57150. for (var i = 0; i < this.soundCollection.length; i++) {
  57151. this.soundCollection[i].switchPanningModelToEqualPower();
  57152. }
  57153. }
  57154. };
  57155. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57156. if (this._connectedAnalyser) {
  57157. this._connectedAnalyser.stopDebugCanvas();
  57158. }
  57159. this._connectedAnalyser = analyser;
  57160. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57161. this._outputAudioNode.disconnect();
  57162. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57163. }
  57164. };
  57165. return SoundTrack;
  57166. }());
  57167. BABYLON.SoundTrack = SoundTrack;
  57168. })(BABYLON || (BABYLON = {}));
  57169. //# sourceMappingURL=babylon.soundtrack.js.map
  57170. var BABYLON;
  57171. (function (BABYLON) {
  57172. var Analyser = /** @class */ (function () {
  57173. function Analyser(scene) {
  57174. this.SMOOTHING = 0.75;
  57175. this.FFT_SIZE = 512;
  57176. this.BARGRAPHAMPLITUDE = 256;
  57177. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57178. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57179. this._scene = scene;
  57180. this._audioEngine = BABYLON.Engine.audioEngine;
  57181. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57182. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57183. this._webAudioAnalyser.minDecibels = -140;
  57184. this._webAudioAnalyser.maxDecibels = 0;
  57185. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57186. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57187. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57188. }
  57189. }
  57190. Analyser.prototype.getFrequencyBinCount = function () {
  57191. if (this._audioEngine.canUseWebAudio) {
  57192. return this._webAudioAnalyser.frequencyBinCount;
  57193. }
  57194. else {
  57195. return 0;
  57196. }
  57197. };
  57198. Analyser.prototype.getByteFrequencyData = function () {
  57199. if (this._audioEngine.canUseWebAudio) {
  57200. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57201. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57202. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57203. }
  57204. return this._byteFreqs;
  57205. };
  57206. Analyser.prototype.getByteTimeDomainData = function () {
  57207. if (this._audioEngine.canUseWebAudio) {
  57208. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57209. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57210. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57211. }
  57212. return this._byteTime;
  57213. };
  57214. Analyser.prototype.getFloatFrequencyData = function () {
  57215. if (this._audioEngine.canUseWebAudio) {
  57216. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57217. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57218. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57219. }
  57220. return this._floatFreqs;
  57221. };
  57222. Analyser.prototype.drawDebugCanvas = function () {
  57223. var _this = this;
  57224. if (this._audioEngine.canUseWebAudio) {
  57225. if (!this._debugCanvas) {
  57226. this._debugCanvas = document.createElement("canvas");
  57227. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57228. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57229. this._debugCanvas.style.position = "absolute";
  57230. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57231. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57232. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57233. document.body.appendChild(this._debugCanvas);
  57234. this._registerFunc = function () {
  57235. _this.drawDebugCanvas();
  57236. };
  57237. this._scene.registerBeforeRender(this._registerFunc);
  57238. }
  57239. if (this._registerFunc && this._debugCanvasContext) {
  57240. var workingArray = this.getByteFrequencyData();
  57241. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57242. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57243. // Draw the frequency domain chart.
  57244. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57245. var value = workingArray[i];
  57246. var percent = value / this.BARGRAPHAMPLITUDE;
  57247. var height = this.DEBUGCANVASSIZE.height * percent;
  57248. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57249. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57250. var hue = i / this.getFrequencyBinCount() * 360;
  57251. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57252. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57253. }
  57254. }
  57255. }
  57256. };
  57257. Analyser.prototype.stopDebugCanvas = function () {
  57258. if (this._debugCanvas) {
  57259. if (this._registerFunc) {
  57260. this._scene.unregisterBeforeRender(this._registerFunc);
  57261. this._registerFunc = null;
  57262. }
  57263. document.body.removeChild(this._debugCanvas);
  57264. this._debugCanvas = null;
  57265. this._debugCanvasContext = null;
  57266. }
  57267. };
  57268. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57269. if (this._audioEngine.canUseWebAudio) {
  57270. inputAudioNode.connect(this._webAudioAnalyser);
  57271. this._webAudioAnalyser.connect(outputAudioNode);
  57272. }
  57273. };
  57274. Analyser.prototype.dispose = function () {
  57275. if (this._audioEngine.canUseWebAudio) {
  57276. this._webAudioAnalyser.disconnect();
  57277. }
  57278. };
  57279. return Analyser;
  57280. }());
  57281. BABYLON.Analyser = Analyser;
  57282. })(BABYLON || (BABYLON = {}));
  57283. //# sourceMappingURL=babylon.analyser.js.map
  57284. var BABYLON;
  57285. (function (BABYLON) {
  57286. var CubeTexture = /** @class */ (function (_super) {
  57287. __extends(CubeTexture, _super);
  57288. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57289. if (extensions === void 0) { extensions = null; }
  57290. if (noMipmap === void 0) { noMipmap = false; }
  57291. if (files === void 0) { files = null; }
  57292. if (onLoad === void 0) { onLoad = null; }
  57293. if (onError === void 0) { onError = null; }
  57294. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57295. if (prefiltered === void 0) { prefiltered = false; }
  57296. if (forcedExtension === void 0) { forcedExtension = null; }
  57297. var _this = _super.call(this, scene) || this;
  57298. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57299. /**
  57300. * Gets or sets the center of the bounding box associated with the cube texture
  57301. * It must define where the camera used to render the texture was set
  57302. */
  57303. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57304. _this.name = rootUrl;
  57305. _this.url = rootUrl;
  57306. _this._noMipmap = noMipmap;
  57307. _this.hasAlpha = false;
  57308. _this._format = format;
  57309. _this._prefiltered = prefiltered;
  57310. _this.isCube = true;
  57311. _this._textureMatrix = BABYLON.Matrix.Identity();
  57312. if (prefiltered) {
  57313. _this.gammaSpace = false;
  57314. }
  57315. if (!rootUrl && !files) {
  57316. return _this;
  57317. }
  57318. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57319. var lastDot = rootUrl.lastIndexOf(".");
  57320. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57321. var isDDS = (extension === ".dds");
  57322. if (!files) {
  57323. if (!isDDS && !extensions) {
  57324. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57325. }
  57326. files = [];
  57327. if (extensions) {
  57328. for (var index = 0; index < extensions.length; index++) {
  57329. files.push(rootUrl + extensions[index]);
  57330. }
  57331. }
  57332. }
  57333. _this._files = files;
  57334. if (!_this._texture) {
  57335. if (!scene.useDelayedTextureLoading) {
  57336. if (prefiltered) {
  57337. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57338. }
  57339. else {
  57340. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57341. }
  57342. }
  57343. else {
  57344. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57345. }
  57346. }
  57347. else if (onLoad) {
  57348. if (_this._texture.isReady) {
  57349. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57350. }
  57351. else {
  57352. _this._texture.onLoadedObservable.add(onLoad);
  57353. }
  57354. }
  57355. return _this;
  57356. }
  57357. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57358. get: function () {
  57359. return this._boundingBoxSize;
  57360. },
  57361. /**
  57362. * Gets or sets the size of the bounding box associated with the cube texture
  57363. * When defined, the cubemap will switch to local mode
  57364. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57365. * @example https://www.babylonjs-playground.com/#RNASML
  57366. */
  57367. set: function (value) {
  57368. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57369. return;
  57370. }
  57371. this._boundingBoxSize = value;
  57372. var scene = this.getScene();
  57373. if (scene) {
  57374. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57375. }
  57376. },
  57377. enumerable: true,
  57378. configurable: true
  57379. });
  57380. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57381. var rootUrlKey = "";
  57382. files.forEach(function (url) { return rootUrlKey += url; });
  57383. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57384. };
  57385. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57386. if (forcedExtension === void 0) { forcedExtension = null; }
  57387. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57388. };
  57389. // Methods
  57390. CubeTexture.prototype.delayLoad = function () {
  57391. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57392. return;
  57393. }
  57394. var scene = this.getScene();
  57395. if (!scene) {
  57396. return;
  57397. }
  57398. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57399. this._texture = this._getFromCache(this.url, this._noMipmap);
  57400. if (!this._texture) {
  57401. if (this._prefiltered) {
  57402. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57403. }
  57404. else {
  57405. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57406. }
  57407. }
  57408. };
  57409. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57410. return this._textureMatrix;
  57411. };
  57412. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57413. this._textureMatrix = value;
  57414. };
  57415. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57416. var texture = BABYLON.SerializationHelper.Parse(function () {
  57417. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57418. }, parsedTexture, scene);
  57419. // Local Cubemaps
  57420. if (parsedTexture.boundingBoxPosition) {
  57421. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57422. }
  57423. if (parsedTexture.boundingBoxSize) {
  57424. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57425. }
  57426. // Animations
  57427. if (parsedTexture.animations) {
  57428. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57429. var parsedAnimation = parsedTexture.animations[animationIndex];
  57430. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57431. }
  57432. }
  57433. return texture;
  57434. };
  57435. CubeTexture.prototype.clone = function () {
  57436. var _this = this;
  57437. return BABYLON.SerializationHelper.Clone(function () {
  57438. var scene = _this.getScene();
  57439. if (!scene) {
  57440. return _this;
  57441. }
  57442. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57443. }, this);
  57444. };
  57445. return CubeTexture;
  57446. }(BABYLON.BaseTexture));
  57447. BABYLON.CubeTexture = CubeTexture;
  57448. })(BABYLON || (BABYLON = {}));
  57449. //# sourceMappingURL=babylon.cubeTexture.js.map
  57450. var BABYLON;
  57451. (function (BABYLON) {
  57452. var RenderTargetTexture = /** @class */ (function (_super) {
  57453. __extends(RenderTargetTexture, _super);
  57454. /**
  57455. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57456. * or used a shadow, depth texture...
  57457. * @param name The friendly name of the texture
  57458. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  57459. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57460. * @param generateMipMaps True if mip maps need to be generated after render.
  57461. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57462. * @param type The type of the buffer in the RTT (int, half float, float...)
  57463. * @param isCube True if a cube texture needs to be created
  57464. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57465. * @param generateDepthBuffer True to generate a depth buffer
  57466. * @param generateStencilBuffer True to generate a stencil buffer
  57467. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57468. */
  57469. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57470. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57471. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57472. if (isCube === void 0) { isCube = false; }
  57473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57474. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57475. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57476. if (isMulti === void 0) { isMulti = false; }
  57477. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57478. _this.isCube = isCube;
  57479. /**
  57480. * Use this list to define the list of mesh you want to render.
  57481. */
  57482. _this.renderList = new Array();
  57483. _this.renderParticles = true;
  57484. _this.renderSprites = false;
  57485. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57486. _this.ignoreCameraViewport = false;
  57487. // Events
  57488. /**
  57489. * An event triggered when the texture is unbind.
  57490. * @type {BABYLON.Observable}
  57491. */
  57492. _this.onBeforeBindObservable = new BABYLON.Observable();
  57493. /**
  57494. * An event triggered when the texture is unbind.
  57495. * @type {BABYLON.Observable}
  57496. */
  57497. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57498. /**
  57499. * An event triggered before rendering the texture
  57500. * @type {BABYLON.Observable}
  57501. */
  57502. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57503. /**
  57504. * An event triggered after rendering the texture
  57505. * @type {BABYLON.Observable}
  57506. */
  57507. _this.onAfterRenderObservable = new BABYLON.Observable();
  57508. /**
  57509. * An event triggered after the texture clear
  57510. * @type {BABYLON.Observable}
  57511. */
  57512. _this.onClearObservable = new BABYLON.Observable();
  57513. _this._currentRefreshId = -1;
  57514. _this._refreshRate = 1;
  57515. _this._samples = 1;
  57516. /**
  57517. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57518. * It must define where the camera used to render the texture is set
  57519. */
  57520. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57521. scene = _this.getScene();
  57522. if (!scene) {
  57523. return _this;
  57524. }
  57525. _this._engine = scene.getEngine();
  57526. _this.name = name;
  57527. _this.isRenderTarget = true;
  57528. _this._initialSizeParameter = size;
  57529. _this._processSizeParameter(size);
  57530. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57531. });
  57532. _this._generateMipMaps = generateMipMaps ? true : false;
  57533. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57534. // Rendering groups
  57535. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57536. if (isMulti) {
  57537. return _this;
  57538. }
  57539. _this._renderTargetOptions = {
  57540. generateMipMaps: generateMipMaps,
  57541. type: type,
  57542. samplingMode: samplingMode,
  57543. generateDepthBuffer: generateDepthBuffer,
  57544. generateStencilBuffer: generateStencilBuffer
  57545. };
  57546. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57547. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57548. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57549. }
  57550. if (isCube) {
  57551. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57552. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57553. _this._textureMatrix = BABYLON.Matrix.Identity();
  57554. }
  57555. else {
  57556. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57557. }
  57558. return _this;
  57559. }
  57560. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57561. get: function () {
  57562. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57563. },
  57564. enumerable: true,
  57565. configurable: true
  57566. });
  57567. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57568. get: function () {
  57569. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57570. },
  57571. enumerable: true,
  57572. configurable: true
  57573. });
  57574. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57575. get: function () {
  57576. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57577. },
  57578. enumerable: true,
  57579. configurable: true
  57580. });
  57581. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57582. set: function (callback) {
  57583. if (this._onAfterUnbindObserver) {
  57584. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57585. }
  57586. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57587. },
  57588. enumerable: true,
  57589. configurable: true
  57590. });
  57591. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57592. set: function (callback) {
  57593. if (this._onBeforeRenderObserver) {
  57594. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57595. }
  57596. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57597. },
  57598. enumerable: true,
  57599. configurable: true
  57600. });
  57601. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57602. set: function (callback) {
  57603. if (this._onAfterRenderObserver) {
  57604. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57605. }
  57606. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57607. },
  57608. enumerable: true,
  57609. configurable: true
  57610. });
  57611. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57612. set: function (callback) {
  57613. if (this._onClearObserver) {
  57614. this.onClearObservable.remove(this._onClearObserver);
  57615. }
  57616. this._onClearObserver = this.onClearObservable.add(callback);
  57617. },
  57618. enumerable: true,
  57619. configurable: true
  57620. });
  57621. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57622. get: function () {
  57623. return this._renderTargetOptions;
  57624. },
  57625. enumerable: true,
  57626. configurable: true
  57627. });
  57628. RenderTargetTexture.prototype._onRatioRescale = function () {
  57629. if (this._sizeRatio) {
  57630. this.resize(this._initialSizeParameter);
  57631. }
  57632. };
  57633. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57634. get: function () {
  57635. return this._boundingBoxSize;
  57636. },
  57637. /**
  57638. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57639. * When defined, the cubemap will switch to local mode
  57640. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57641. * @example https://www.babylonjs-playground.com/#RNASML
  57642. */
  57643. set: function (value) {
  57644. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57645. return;
  57646. }
  57647. this._boundingBoxSize = value;
  57648. var scene = this.getScene();
  57649. if (scene) {
  57650. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57651. }
  57652. },
  57653. enumerable: true,
  57654. configurable: true
  57655. });
  57656. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57657. if (size.ratio) {
  57658. this._sizeRatio = size.ratio;
  57659. this._size = {
  57660. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57661. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57662. };
  57663. }
  57664. else {
  57665. this._size = size;
  57666. }
  57667. };
  57668. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57669. get: function () {
  57670. return this._samples;
  57671. },
  57672. set: function (value) {
  57673. if (this._samples === value) {
  57674. return;
  57675. }
  57676. var scene = this.getScene();
  57677. if (!scene) {
  57678. return;
  57679. }
  57680. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57681. },
  57682. enumerable: true,
  57683. configurable: true
  57684. });
  57685. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57686. this._currentRefreshId = -1;
  57687. };
  57688. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57689. get: function () {
  57690. return this._refreshRate;
  57691. },
  57692. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57693. set: function (value) {
  57694. this._refreshRate = value;
  57695. this.resetRefreshCounter();
  57696. },
  57697. enumerable: true,
  57698. configurable: true
  57699. });
  57700. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57701. if (!this._postProcessManager) {
  57702. var scene = this.getScene();
  57703. if (!scene) {
  57704. return;
  57705. }
  57706. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57707. this._postProcesses = new Array();
  57708. }
  57709. this._postProcesses.push(postProcess);
  57710. this._postProcesses[0].autoClear = false;
  57711. };
  57712. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57713. if (!this._postProcesses) {
  57714. return;
  57715. }
  57716. if (dispose) {
  57717. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57718. var postProcess = _a[_i];
  57719. postProcess.dispose();
  57720. }
  57721. }
  57722. this._postProcesses = [];
  57723. };
  57724. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57725. if (!this._postProcesses) {
  57726. return;
  57727. }
  57728. var index = this._postProcesses.indexOf(postProcess);
  57729. if (index === -1) {
  57730. return;
  57731. }
  57732. this._postProcesses.splice(index, 1);
  57733. if (this._postProcesses.length > 0) {
  57734. this._postProcesses[0].autoClear = false;
  57735. }
  57736. };
  57737. RenderTargetTexture.prototype._shouldRender = function () {
  57738. if (this._currentRefreshId === -1) {
  57739. this._currentRefreshId = 1;
  57740. return true;
  57741. }
  57742. if (this.refreshRate === this._currentRefreshId) {
  57743. this._currentRefreshId = 1;
  57744. return true;
  57745. }
  57746. this._currentRefreshId++;
  57747. return false;
  57748. };
  57749. RenderTargetTexture.prototype.getRenderSize = function () {
  57750. if (this._size.width) {
  57751. return this._size.width;
  57752. }
  57753. return this._size;
  57754. };
  57755. RenderTargetTexture.prototype.getRenderWidth = function () {
  57756. if (this._size.width) {
  57757. return this._size.width;
  57758. }
  57759. return this._size;
  57760. };
  57761. RenderTargetTexture.prototype.getRenderHeight = function () {
  57762. if (this._size.width) {
  57763. return this._size.height;
  57764. }
  57765. return this._size;
  57766. };
  57767. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57768. get: function () {
  57769. return true;
  57770. },
  57771. enumerable: true,
  57772. configurable: true
  57773. });
  57774. RenderTargetTexture.prototype.scale = function (ratio) {
  57775. var newSize = this.getRenderSize() * ratio;
  57776. this.resize(newSize);
  57777. };
  57778. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57779. if (this.isCube) {
  57780. return this._textureMatrix;
  57781. }
  57782. return _super.prototype.getReflectionTextureMatrix.call(this);
  57783. };
  57784. RenderTargetTexture.prototype.resize = function (size) {
  57785. this.releaseInternalTexture();
  57786. var scene = this.getScene();
  57787. if (!scene) {
  57788. return;
  57789. }
  57790. this._processSizeParameter(size);
  57791. if (this.isCube) {
  57792. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57793. }
  57794. else {
  57795. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57796. }
  57797. };
  57798. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57799. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57800. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57801. var scene = this.getScene();
  57802. if (!scene) {
  57803. return;
  57804. }
  57805. var engine = scene.getEngine();
  57806. if (this.useCameraPostProcesses !== undefined) {
  57807. useCameraPostProcess = this.useCameraPostProcesses;
  57808. }
  57809. if (this._waitingRenderList) {
  57810. this.renderList = [];
  57811. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57812. var id = this._waitingRenderList[index];
  57813. var mesh_1 = scene.getMeshByID(id);
  57814. if (mesh_1) {
  57815. this.renderList.push(mesh_1);
  57816. }
  57817. }
  57818. delete this._waitingRenderList;
  57819. }
  57820. // Is predicate defined?
  57821. if (this.renderListPredicate) {
  57822. if (this.renderList) {
  57823. this.renderList.splice(0); // Clear previous renderList
  57824. }
  57825. else {
  57826. this.renderList = [];
  57827. }
  57828. var scene = this.getScene();
  57829. if (!scene) {
  57830. return;
  57831. }
  57832. var sceneMeshes = scene.meshes;
  57833. for (var index = 0; index < sceneMeshes.length; index++) {
  57834. var mesh = sceneMeshes[index];
  57835. if (this.renderListPredicate(mesh)) {
  57836. this.renderList.push(mesh);
  57837. }
  57838. }
  57839. }
  57840. this.onBeforeBindObservable.notifyObservers(this);
  57841. // Set custom projection.
  57842. // Needs to be before binding to prevent changing the aspect ratio.
  57843. var camera;
  57844. if (this.activeCamera) {
  57845. camera = this.activeCamera;
  57846. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57847. if (this.activeCamera !== scene.activeCamera) {
  57848. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57849. }
  57850. }
  57851. else {
  57852. camera = scene.activeCamera;
  57853. if (camera) {
  57854. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57855. }
  57856. }
  57857. // Prepare renderingManager
  57858. this._renderingManager.reset();
  57859. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57860. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57861. var sceneRenderId = scene.getRenderId();
  57862. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57863. var mesh = currentRenderList[meshIndex];
  57864. if (mesh) {
  57865. if (!mesh.isReady(this.refreshRate === 0)) {
  57866. this.resetRefreshCounter();
  57867. continue;
  57868. }
  57869. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57870. var isMasked = void 0;
  57871. if (!this.renderList && camera) {
  57872. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57873. }
  57874. else {
  57875. isMasked = false;
  57876. }
  57877. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57878. mesh._activate(sceneRenderId);
  57879. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57880. var subMesh = mesh.subMeshes[subIndex];
  57881. scene._activeIndices.addCount(subMesh.indexCount, false);
  57882. this._renderingManager.dispatch(subMesh, mesh);
  57883. }
  57884. }
  57885. }
  57886. }
  57887. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57888. var particleSystem = scene.particleSystems[particleIndex];
  57889. var emitter = particleSystem.emitter;
  57890. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57891. continue;
  57892. }
  57893. if (currentRenderList.indexOf(emitter) >= 0) {
  57894. this._renderingManager.dispatchParticles(particleSystem);
  57895. }
  57896. }
  57897. if (this.isCube) {
  57898. for (var face = 0; face < 6; face++) {
  57899. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57900. scene.incrementRenderId();
  57901. scene.resetCachedMaterial();
  57902. }
  57903. }
  57904. else {
  57905. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57906. }
  57907. this.onAfterUnbindObservable.notifyObservers(this);
  57908. if (scene.activeCamera) {
  57909. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57910. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57911. }
  57912. engine.setViewport(scene.activeCamera.viewport);
  57913. }
  57914. scene.resetCachedMaterial();
  57915. };
  57916. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57917. var minimum = 128;
  57918. var x = renderDimension * scale;
  57919. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57920. // Ensure we don't exceed the render dimension (while staying POT)
  57921. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57922. };
  57923. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57924. var _this = this;
  57925. if (!this._texture) {
  57926. return;
  57927. }
  57928. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57929. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57930. });
  57931. };
  57932. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57933. var scene = this.getScene();
  57934. if (!scene) {
  57935. return;
  57936. }
  57937. var engine = scene.getEngine();
  57938. if (!this._texture) {
  57939. return;
  57940. }
  57941. // Bind
  57942. if (this._postProcessManager) {
  57943. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57944. }
  57945. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57946. if (this._texture) {
  57947. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57948. }
  57949. }
  57950. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57951. // Clear
  57952. if (this.onClearObservable.hasObservers()) {
  57953. this.onClearObservable.notifyObservers(engine);
  57954. }
  57955. else {
  57956. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57957. }
  57958. if (!this._doNotChangeAspectRatio) {
  57959. scene.updateTransformMatrix(true);
  57960. }
  57961. // Render
  57962. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57963. if (this._postProcessManager) {
  57964. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57965. }
  57966. else if (useCameraPostProcess) {
  57967. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57968. }
  57969. if (!this._doNotChangeAspectRatio) {
  57970. scene.updateTransformMatrix(true);
  57971. }
  57972. // Dump ?
  57973. if (dumpForDebug) {
  57974. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57975. }
  57976. // Unbind
  57977. if (!this.isCube || faceIndex === 5) {
  57978. if (this.isCube) {
  57979. if (faceIndex === 5) {
  57980. engine.generateMipMapsForCubemap(this._texture);
  57981. }
  57982. }
  57983. this.unbindFrameBuffer(engine, faceIndex);
  57984. }
  57985. else {
  57986. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57987. }
  57988. };
  57989. /**
  57990. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57991. * This allowed control for front to back rendering or reversly depending of the special needs.
  57992. *
  57993. * @param renderingGroupId The rendering group id corresponding to its index
  57994. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57995. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57996. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57997. */
  57998. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57999. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58000. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58001. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58002. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58003. };
  58004. /**
  58005. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58006. *
  58007. * @param renderingGroupId The rendering group id corresponding to its index
  58008. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58009. */
  58010. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58011. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58012. };
  58013. RenderTargetTexture.prototype.clone = function () {
  58014. var textureSize = this.getSize();
  58015. 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);
  58016. // Base texture
  58017. newTexture.hasAlpha = this.hasAlpha;
  58018. newTexture.level = this.level;
  58019. // RenderTarget Texture
  58020. newTexture.coordinatesMode = this.coordinatesMode;
  58021. if (this.renderList) {
  58022. newTexture.renderList = this.renderList.slice(0);
  58023. }
  58024. return newTexture;
  58025. };
  58026. RenderTargetTexture.prototype.serialize = function () {
  58027. if (!this.name) {
  58028. return null;
  58029. }
  58030. var serializationObject = _super.prototype.serialize.call(this);
  58031. serializationObject.renderTargetSize = this.getRenderSize();
  58032. serializationObject.renderList = [];
  58033. if (this.renderList) {
  58034. for (var index = 0; index < this.renderList.length; index++) {
  58035. serializationObject.renderList.push(this.renderList[index].id);
  58036. }
  58037. }
  58038. return serializationObject;
  58039. };
  58040. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58041. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58042. var objBuffer = this.getInternalTexture();
  58043. var scene = this.getScene();
  58044. if (objBuffer && scene) {
  58045. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58046. }
  58047. };
  58048. RenderTargetTexture.prototype.dispose = function () {
  58049. if (this._postProcessManager) {
  58050. this._postProcessManager.dispose();
  58051. this._postProcessManager = null;
  58052. }
  58053. this.clearPostProcesses(true);
  58054. if (this._resizeObserver) {
  58055. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58056. this._resizeObserver = null;
  58057. }
  58058. this.renderList = null;
  58059. // Remove from custom render targets
  58060. var scene = this.getScene();
  58061. if (!scene) {
  58062. return;
  58063. }
  58064. var index = scene.customRenderTargets.indexOf(this);
  58065. if (index >= 0) {
  58066. scene.customRenderTargets.splice(index, 1);
  58067. }
  58068. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58069. var camera = _a[_i];
  58070. index = camera.customRenderTargets.indexOf(this);
  58071. if (index >= 0) {
  58072. camera.customRenderTargets.splice(index, 1);
  58073. }
  58074. }
  58075. _super.prototype.dispose.call(this);
  58076. };
  58077. RenderTargetTexture.prototype._rebuild = function () {
  58078. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58079. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58080. }
  58081. if (this._postProcessManager) {
  58082. this._postProcessManager._rebuild();
  58083. }
  58084. };
  58085. /**
  58086. * Clear the info related to rendering groups preventing retention point in material dispose.
  58087. */
  58088. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58089. if (this._renderingManager) {
  58090. this._renderingManager.freeRenderingGroups();
  58091. }
  58092. };
  58093. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58094. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58095. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58096. return RenderTargetTexture;
  58097. }(BABYLON.Texture));
  58098. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58099. })(BABYLON || (BABYLON = {}));
  58100. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58101. var BABYLON;
  58102. (function (BABYLON) {
  58103. ;
  58104. var MultiRenderTarget = /** @class */ (function (_super) {
  58105. __extends(MultiRenderTarget, _super);
  58106. function MultiRenderTarget(name, size, count, scene, options) {
  58107. var _this = this;
  58108. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58109. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58110. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58111. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58112. _this._engine = scene.getEngine();
  58113. if (!_this.isSupported) {
  58114. _this.dispose();
  58115. return;
  58116. }
  58117. var types = [];
  58118. var samplingModes = [];
  58119. for (var i = 0; i < count; i++) {
  58120. if (options && options.types && options.types[i] !== undefined) {
  58121. types.push(options.types[i]);
  58122. }
  58123. else {
  58124. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58125. }
  58126. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58127. samplingModes.push(options.samplingModes[i]);
  58128. }
  58129. else {
  58130. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58131. }
  58132. }
  58133. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58134. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58135. _this._size = size;
  58136. _this._multiRenderTargetOptions = {
  58137. samplingModes: samplingModes,
  58138. generateMipMaps: generateMipMaps,
  58139. generateDepthBuffer: generateDepthBuffer,
  58140. generateStencilBuffer: generateStencilBuffer,
  58141. generateDepthTexture: generateDepthTexture,
  58142. types: types,
  58143. textureCount: count
  58144. };
  58145. _this._createInternalTextures();
  58146. _this._createTextures();
  58147. return _this;
  58148. }
  58149. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58150. get: function () {
  58151. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58152. },
  58153. enumerable: true,
  58154. configurable: true
  58155. });
  58156. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58157. get: function () {
  58158. return this._textures;
  58159. },
  58160. enumerable: true,
  58161. configurable: true
  58162. });
  58163. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58164. get: function () {
  58165. return this._textures[this._textures.length - 1];
  58166. },
  58167. enumerable: true,
  58168. configurable: true
  58169. });
  58170. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58171. set: function (wrap) {
  58172. if (this._textures) {
  58173. for (var i = 0; i < this._textures.length; i++) {
  58174. this._textures[i].wrapU = wrap;
  58175. }
  58176. }
  58177. },
  58178. enumerable: true,
  58179. configurable: true
  58180. });
  58181. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58182. set: function (wrap) {
  58183. if (this._textures) {
  58184. for (var i = 0; i < this._textures.length; i++) {
  58185. this._textures[i].wrapV = wrap;
  58186. }
  58187. }
  58188. },
  58189. enumerable: true,
  58190. configurable: true
  58191. });
  58192. MultiRenderTarget.prototype._rebuild = function () {
  58193. this.releaseInternalTextures();
  58194. this._createInternalTextures();
  58195. for (var i = 0; i < this._internalTextures.length; i++) {
  58196. var texture = this._textures[i];
  58197. texture._texture = this._internalTextures[i];
  58198. }
  58199. // Keeps references to frame buffer and stencil/depth buffer
  58200. this._texture = this._internalTextures[0];
  58201. };
  58202. MultiRenderTarget.prototype._createInternalTextures = function () {
  58203. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58204. };
  58205. MultiRenderTarget.prototype._createTextures = function () {
  58206. this._textures = [];
  58207. for (var i = 0; i < this._internalTextures.length; i++) {
  58208. var texture = new BABYLON.Texture(null, this.getScene());
  58209. texture._texture = this._internalTextures[i];
  58210. this._textures.push(texture);
  58211. }
  58212. // Keeps references to frame buffer and stencil/depth buffer
  58213. this._texture = this._internalTextures[0];
  58214. };
  58215. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58216. get: function () {
  58217. return this._samples;
  58218. },
  58219. set: function (value) {
  58220. if (this._samples === value) {
  58221. return;
  58222. }
  58223. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58224. },
  58225. enumerable: true,
  58226. configurable: true
  58227. });
  58228. MultiRenderTarget.prototype.resize = function (size) {
  58229. this.releaseInternalTextures();
  58230. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58231. this._createInternalTextures();
  58232. };
  58233. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58234. var _this = this;
  58235. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58236. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58237. });
  58238. };
  58239. MultiRenderTarget.prototype.dispose = function () {
  58240. this.releaseInternalTextures();
  58241. _super.prototype.dispose.call(this);
  58242. };
  58243. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58244. if (!this._internalTextures) {
  58245. return;
  58246. }
  58247. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58248. if (this._internalTextures[i] !== undefined) {
  58249. this._internalTextures[i].dispose();
  58250. this._internalTextures.splice(i, 1);
  58251. }
  58252. }
  58253. };
  58254. return MultiRenderTarget;
  58255. }(BABYLON.RenderTargetTexture));
  58256. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58257. })(BABYLON || (BABYLON = {}));
  58258. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58259. var BABYLON;
  58260. (function (BABYLON) {
  58261. var MirrorTexture = /** @class */ (function (_super) {
  58262. __extends(MirrorTexture, _super);
  58263. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58264. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58266. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58267. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58268. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58269. _this._transformMatrix = BABYLON.Matrix.Zero();
  58270. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58271. _this._adaptiveBlurKernel = 0;
  58272. _this._blurKernelX = 0;
  58273. _this._blurKernelY = 0;
  58274. _this._blurRatio = 1.0;
  58275. _this.ignoreCameraViewport = true;
  58276. _this.onBeforeRenderObservable.add(function () {
  58277. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58278. _this._savedViewMatrix = scene.getViewMatrix();
  58279. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58280. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58281. scene.clipPlane = _this.mirrorPlane;
  58282. scene.getEngine().cullBackFaces = false;
  58283. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58284. });
  58285. _this.onAfterRenderObservable.add(function () {
  58286. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58287. scene.getEngine().cullBackFaces = true;
  58288. scene._mirroredCameraPosition = null;
  58289. delete scene.clipPlane;
  58290. });
  58291. return _this;
  58292. }
  58293. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58294. get: function () {
  58295. return this._blurRatio;
  58296. },
  58297. set: function (value) {
  58298. if (this._blurRatio === value) {
  58299. return;
  58300. }
  58301. this._blurRatio = value;
  58302. this._preparePostProcesses();
  58303. },
  58304. enumerable: true,
  58305. configurable: true
  58306. });
  58307. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58308. set: function (value) {
  58309. this._adaptiveBlurKernel = value;
  58310. this._autoComputeBlurKernel();
  58311. },
  58312. enumerable: true,
  58313. configurable: true
  58314. });
  58315. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58316. set: function (value) {
  58317. this.blurKernelX = value;
  58318. this.blurKernelY = value;
  58319. },
  58320. enumerable: true,
  58321. configurable: true
  58322. });
  58323. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58324. get: function () {
  58325. return this._blurKernelX;
  58326. },
  58327. set: function (value) {
  58328. if (this._blurKernelX === value) {
  58329. return;
  58330. }
  58331. this._blurKernelX = value;
  58332. this._preparePostProcesses();
  58333. },
  58334. enumerable: true,
  58335. configurable: true
  58336. });
  58337. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58338. get: function () {
  58339. return this._blurKernelY;
  58340. },
  58341. set: function (value) {
  58342. if (this._blurKernelY === value) {
  58343. return;
  58344. }
  58345. this._blurKernelY = value;
  58346. this._preparePostProcesses();
  58347. },
  58348. enumerable: true,
  58349. configurable: true
  58350. });
  58351. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58352. var engine = this.getScene().getEngine();
  58353. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58354. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58355. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58356. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58357. };
  58358. MirrorTexture.prototype._onRatioRescale = function () {
  58359. if (this._sizeRatio) {
  58360. this.resize(this._initialSizeParameter);
  58361. if (!this._adaptiveBlurKernel) {
  58362. this._preparePostProcesses();
  58363. }
  58364. }
  58365. if (this._adaptiveBlurKernel) {
  58366. this._autoComputeBlurKernel();
  58367. }
  58368. };
  58369. MirrorTexture.prototype._preparePostProcesses = function () {
  58370. this.clearPostProcesses(true);
  58371. if (this._blurKernelX && this._blurKernelY) {
  58372. var engine = this.getScene().getEngine();
  58373. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58374. 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);
  58375. this._blurX.autoClear = false;
  58376. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58377. this._blurX.inputTexture = this._texture;
  58378. }
  58379. else {
  58380. this._blurX.alwaysForcePOT = true;
  58381. }
  58382. 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);
  58383. this._blurY.autoClear = false;
  58384. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58385. this.addPostProcess(this._blurX);
  58386. this.addPostProcess(this._blurY);
  58387. }
  58388. else {
  58389. if (this._blurY) {
  58390. this.removePostProcess(this._blurY);
  58391. this._blurY.dispose();
  58392. this._blurY = null;
  58393. }
  58394. if (this._blurX) {
  58395. this.removePostProcess(this._blurX);
  58396. this._blurX.dispose();
  58397. this._blurX = null;
  58398. }
  58399. }
  58400. };
  58401. MirrorTexture.prototype.clone = function () {
  58402. var scene = this.getScene();
  58403. if (!scene) {
  58404. return this;
  58405. }
  58406. var textureSize = this.getSize();
  58407. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58408. // Base texture
  58409. newTexture.hasAlpha = this.hasAlpha;
  58410. newTexture.level = this.level;
  58411. // Mirror Texture
  58412. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58413. if (this.renderList) {
  58414. newTexture.renderList = this.renderList.slice(0);
  58415. }
  58416. return newTexture;
  58417. };
  58418. MirrorTexture.prototype.serialize = function () {
  58419. if (!this.name) {
  58420. return null;
  58421. }
  58422. var serializationObject = _super.prototype.serialize.call(this);
  58423. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58424. return serializationObject;
  58425. };
  58426. return MirrorTexture;
  58427. }(BABYLON.RenderTargetTexture));
  58428. BABYLON.MirrorTexture = MirrorTexture;
  58429. })(BABYLON || (BABYLON = {}));
  58430. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58431. var BABYLON;
  58432. (function (BABYLON) {
  58433. /**
  58434. * Creates a refraction texture used by refraction channel of the standard material.
  58435. * @param name the texture name
  58436. * @param size size of the underlying texture
  58437. * @param scene root scene
  58438. */
  58439. var RefractionTexture = /** @class */ (function (_super) {
  58440. __extends(RefractionTexture, _super);
  58441. function RefractionTexture(name, size, scene, generateMipMaps) {
  58442. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58443. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58444. _this.depth = 2.0;
  58445. _this.onBeforeRenderObservable.add(function () {
  58446. scene.clipPlane = _this.refractionPlane;
  58447. });
  58448. _this.onAfterRenderObservable.add(function () {
  58449. delete scene.clipPlane;
  58450. });
  58451. return _this;
  58452. }
  58453. RefractionTexture.prototype.clone = function () {
  58454. var scene = this.getScene();
  58455. if (!scene) {
  58456. return this;
  58457. }
  58458. var textureSize = this.getSize();
  58459. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58460. // Base texture
  58461. newTexture.hasAlpha = this.hasAlpha;
  58462. newTexture.level = this.level;
  58463. // Refraction Texture
  58464. newTexture.refractionPlane = this.refractionPlane.clone();
  58465. if (this.renderList) {
  58466. newTexture.renderList = this.renderList.slice(0);
  58467. }
  58468. newTexture.depth = this.depth;
  58469. return newTexture;
  58470. };
  58471. RefractionTexture.prototype.serialize = function () {
  58472. if (!this.name) {
  58473. return null;
  58474. }
  58475. var serializationObject = _super.prototype.serialize.call(this);
  58476. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58477. serializationObject.depth = this.depth;
  58478. return serializationObject;
  58479. };
  58480. return RefractionTexture;
  58481. }(BABYLON.RenderTargetTexture));
  58482. BABYLON.RefractionTexture = RefractionTexture;
  58483. })(BABYLON || (BABYLON = {}));
  58484. //# sourceMappingURL=babylon.refractionTexture.js.map
  58485. var BABYLON;
  58486. (function (BABYLON) {
  58487. var DynamicTexture = /** @class */ (function (_super) {
  58488. __extends(DynamicTexture, _super);
  58489. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58490. if (scene === void 0) { scene = null; }
  58491. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58492. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58493. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58494. _this.name = name;
  58495. _this._engine = _this.getScene().getEngine();
  58496. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58497. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58498. _this._generateMipMaps = generateMipMaps;
  58499. if (options.getContext) {
  58500. _this._canvas = options;
  58501. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58502. }
  58503. else {
  58504. _this._canvas = document.createElement("canvas");
  58505. if (options.width) {
  58506. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58507. }
  58508. else {
  58509. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58510. }
  58511. }
  58512. var textureSize = _this.getSize();
  58513. _this._canvas.width = textureSize.width;
  58514. _this._canvas.height = textureSize.height;
  58515. _this._context = _this._canvas.getContext("2d");
  58516. return _this;
  58517. }
  58518. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58519. get: function () {
  58520. return true;
  58521. },
  58522. enumerable: true,
  58523. configurable: true
  58524. });
  58525. DynamicTexture.prototype._recreate = function (textureSize) {
  58526. this._canvas.width = textureSize.width;
  58527. this._canvas.height = textureSize.height;
  58528. this.releaseInternalTexture();
  58529. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58530. };
  58531. DynamicTexture.prototype.scale = function (ratio) {
  58532. var textureSize = this.getSize();
  58533. textureSize.width *= ratio;
  58534. textureSize.height *= ratio;
  58535. this._recreate(textureSize);
  58536. };
  58537. DynamicTexture.prototype.scaleTo = function (width, height) {
  58538. var textureSize = this.getSize();
  58539. textureSize.width = width;
  58540. textureSize.height = height;
  58541. this._recreate(textureSize);
  58542. };
  58543. DynamicTexture.prototype.getContext = function () {
  58544. return this._context;
  58545. };
  58546. DynamicTexture.prototype.clear = function () {
  58547. var size = this.getSize();
  58548. this._context.fillRect(0, 0, size.width, size.height);
  58549. };
  58550. DynamicTexture.prototype.update = function (invertY) {
  58551. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58552. };
  58553. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58554. if (update === void 0) { update = true; }
  58555. var size = this.getSize();
  58556. if (clearColor) {
  58557. this._context.fillStyle = clearColor;
  58558. this._context.fillRect(0, 0, size.width, size.height);
  58559. }
  58560. this._context.font = font;
  58561. if (x === null || x === undefined) {
  58562. var textSize = this._context.measureText(text);
  58563. x = (size.width - textSize.width) / 2;
  58564. }
  58565. if (y === null || y === undefined) {
  58566. var fontSize = parseInt((font.replace(/\D/g, '')));
  58567. ;
  58568. y = (size.height / 2) + (fontSize / 3.65);
  58569. }
  58570. this._context.fillStyle = color;
  58571. this._context.fillText(text, x, y);
  58572. if (update) {
  58573. this.update(invertY);
  58574. }
  58575. };
  58576. DynamicTexture.prototype.clone = function () {
  58577. var scene = this.getScene();
  58578. if (!scene) {
  58579. return this;
  58580. }
  58581. var textureSize = this.getSize();
  58582. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58583. // Base texture
  58584. newTexture.hasAlpha = this.hasAlpha;
  58585. newTexture.level = this.level;
  58586. // Dynamic Texture
  58587. newTexture.wrapU = this.wrapU;
  58588. newTexture.wrapV = this.wrapV;
  58589. return newTexture;
  58590. };
  58591. DynamicTexture.prototype._rebuild = function () {
  58592. this.update();
  58593. };
  58594. return DynamicTexture;
  58595. }(BABYLON.Texture));
  58596. BABYLON.DynamicTexture = DynamicTexture;
  58597. })(BABYLON || (BABYLON = {}));
  58598. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58599. var BABYLON;
  58600. (function (BABYLON) {
  58601. var VideoTexture = /** @class */ (function (_super) {
  58602. __extends(VideoTexture, _super);
  58603. /**
  58604. * Creates a video texture.
  58605. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58606. * @param {string | null} name optional name, will detect from video source, if not defined
  58607. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58608. * @param {BABYLON.Scene} scene is obviously the current scene.
  58609. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58610. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58611. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58612. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58613. */
  58614. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58615. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58616. if (invertY === void 0) { invertY = false; }
  58617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58618. if (settings === void 0) { settings = {
  58619. autoPlay: true,
  58620. loop: true,
  58621. autoUpdateTexture: true,
  58622. }; }
  58623. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58624. _this._createInternalTexture = function () {
  58625. if (_this._texture != null) {
  58626. return;
  58627. }
  58628. if (!_this._engine.needPOTTextures ||
  58629. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58630. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58631. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58632. }
  58633. else {
  58634. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58635. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58636. _this._generateMipMaps = false;
  58637. }
  58638. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58639. _this._texture.isReady = true;
  58640. _this._updateInternalTexture();
  58641. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  58642. _this.onLoadObservable.notifyObservers(_this);
  58643. }
  58644. };
  58645. _this.reset = function () {
  58646. if (_this._texture == null) {
  58647. return;
  58648. }
  58649. _this._texture.dispose();
  58650. _this._texture = null;
  58651. };
  58652. _this._updateInternalTexture = function (e) {
  58653. if (_this._texture == null || !_this._texture.isReady) {
  58654. return;
  58655. }
  58656. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58657. return;
  58658. }
  58659. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58660. };
  58661. _this._engine = _this.getScene().getEngine();
  58662. _this._generateMipMaps = generateMipMaps;
  58663. _this._samplingMode = samplingMode;
  58664. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58665. _this.name = name || _this._getName(src);
  58666. _this.video = _this._getVideo(src);
  58667. if (settings.autoPlay !== undefined) {
  58668. _this.video.autoplay = settings.autoPlay;
  58669. }
  58670. if (settings.loop !== undefined) {
  58671. _this.video.loop = settings.loop;
  58672. }
  58673. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58674. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58675. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58676. _this.video.addEventListener("emptied", _this.reset);
  58677. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58678. _this._createInternalTexture();
  58679. }
  58680. return _this;
  58681. }
  58682. VideoTexture.prototype._getName = function (src) {
  58683. if (src instanceof HTMLVideoElement) {
  58684. return src.currentSrc;
  58685. }
  58686. if (typeof src === "object") {
  58687. return src.toString();
  58688. }
  58689. return src;
  58690. };
  58691. ;
  58692. VideoTexture.prototype._getVideo = function (src) {
  58693. if (src instanceof HTMLVideoElement) {
  58694. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58695. return src;
  58696. }
  58697. var video = document.createElement("video");
  58698. if (typeof src === "string") {
  58699. BABYLON.Tools.SetCorsBehavior(src, video);
  58700. video.src = src;
  58701. }
  58702. else {
  58703. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58704. src.forEach(function (url) {
  58705. var source = document.createElement("source");
  58706. source.src = url;
  58707. video.appendChild(source);
  58708. });
  58709. }
  58710. return video;
  58711. };
  58712. ;
  58713. /**
  58714. * Internal method to initiate `update`.
  58715. */
  58716. VideoTexture.prototype._rebuild = function () {
  58717. this.update();
  58718. };
  58719. /**
  58720. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58721. */
  58722. VideoTexture.prototype.update = function () {
  58723. if (!this.autoUpdateTexture) {
  58724. // Expecting user to call `updateTexture` manually
  58725. return;
  58726. }
  58727. this.updateTexture(true);
  58728. };
  58729. /**
  58730. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58731. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58732. */
  58733. VideoTexture.prototype.updateTexture = function (isVisible) {
  58734. if (!isVisible) {
  58735. return;
  58736. }
  58737. if (this.video.paused) {
  58738. return;
  58739. }
  58740. this._updateInternalTexture();
  58741. };
  58742. /**
  58743. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58744. * @param url New url.
  58745. */
  58746. VideoTexture.prototype.updateURL = function (url) {
  58747. this.video.src = url;
  58748. };
  58749. VideoTexture.prototype.dispose = function () {
  58750. _super.prototype.dispose.call(this);
  58751. this.video.removeEventListener("canplay", this._createInternalTexture);
  58752. this.video.removeEventListener("paused", this._updateInternalTexture);
  58753. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58754. this.video.removeEventListener("emptied", this.reset);
  58755. this.video.pause();
  58756. };
  58757. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58758. var video = document.createElement("video");
  58759. var constraintsDeviceId;
  58760. if (constraints && constraints.deviceId) {
  58761. constraintsDeviceId = {
  58762. exact: constraints.deviceId,
  58763. };
  58764. }
  58765. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58766. if (navigator.mediaDevices) {
  58767. navigator.mediaDevices.getUserMedia({ video: constraints })
  58768. .then(function (stream) {
  58769. if (video.mozSrcObject !== undefined) {
  58770. // hack for Firefox < 19
  58771. video.mozSrcObject = stream;
  58772. }
  58773. else {
  58774. video.srcObject = stream;
  58775. }
  58776. var onPlaying = function () {
  58777. if (onReady) {
  58778. onReady(new VideoTexture("video", video, scene, true, true));
  58779. }
  58780. video.removeEventListener("playing", onPlaying);
  58781. };
  58782. video.addEventListener("playing", onPlaying);
  58783. video.play();
  58784. })
  58785. .catch(function (err) {
  58786. BABYLON.Tools.Error(err.name);
  58787. });
  58788. }
  58789. else {
  58790. navigator.getUserMedia =
  58791. navigator.getUserMedia ||
  58792. navigator.webkitGetUserMedia ||
  58793. navigator.mozGetUserMedia ||
  58794. navigator.msGetUserMedia;
  58795. if (navigator.getUserMedia) {
  58796. navigator.getUserMedia({
  58797. video: {
  58798. deviceId: constraintsDeviceId,
  58799. width: {
  58800. min: (constraints && constraints.minWidth) || 256,
  58801. max: (constraints && constraints.maxWidth) || 640,
  58802. },
  58803. height: {
  58804. min: (constraints && constraints.minHeight) || 256,
  58805. max: (constraints && constraints.maxHeight) || 480,
  58806. },
  58807. },
  58808. }, function (stream) {
  58809. if (video.mozSrcObject !== undefined) {
  58810. // hack for Firefox < 19
  58811. video.mozSrcObject = stream;
  58812. }
  58813. else {
  58814. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58815. }
  58816. video.play();
  58817. if (onReady) {
  58818. onReady(new VideoTexture("video", video, scene, true, true));
  58819. }
  58820. }, function (e) {
  58821. BABYLON.Tools.Error(e.name);
  58822. });
  58823. }
  58824. }
  58825. };
  58826. return VideoTexture;
  58827. }(BABYLON.Texture));
  58828. BABYLON.VideoTexture = VideoTexture;
  58829. })(BABYLON || (BABYLON = {}));
  58830. //# sourceMappingURL=babylon.videoTexture.js.map
  58831. var BABYLON;
  58832. (function (BABYLON) {
  58833. var RawTexture = /** @class */ (function (_super) {
  58834. __extends(RawTexture, _super);
  58835. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58836. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58837. if (invertY === void 0) { invertY = false; }
  58838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58839. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58840. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58841. _this.format = format;
  58842. _this._engine = scene.getEngine();
  58843. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58844. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58845. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58846. return _this;
  58847. }
  58848. RawTexture.prototype.update = function (data) {
  58849. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58850. };
  58851. // Statics
  58852. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58853. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58854. if (invertY === void 0) { invertY = false; }
  58855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58856. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58857. };
  58858. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58859. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58860. if (invertY === void 0) { invertY = false; }
  58861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58862. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58863. };
  58864. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58865. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58866. if (invertY === void 0) { invertY = false; }
  58867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58868. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58869. };
  58870. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58871. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58872. if (invertY === void 0) { invertY = false; }
  58873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58874. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58875. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58876. };
  58877. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58878. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58879. if (invertY === void 0) { invertY = false; }
  58880. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58881. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58882. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58883. };
  58884. return RawTexture;
  58885. }(BABYLON.Texture));
  58886. BABYLON.RawTexture = RawTexture;
  58887. })(BABYLON || (BABYLON = {}));
  58888. //# sourceMappingURL=babylon.rawTexture.js.map
  58889. var BABYLON;
  58890. (function (BABYLON) {
  58891. /**
  58892. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58893. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58894. */
  58895. var PostProcess = /** @class */ (function () {
  58896. /**
  58897. * Creates a new instance of @see PostProcess
  58898. * @param name The name of the PostProcess.
  58899. * @param fragmentUrl The url of the fragment shader to be used.
  58900. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58901. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58902. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58903. * @param camera The camera to apply the render pass to.
  58904. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58905. * @param engine The engine which the post process will be applied. (default: current engine)
  58906. * @param reusable If the post process can be reused on the same frame. (default: false)
  58907. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58908. * @param textureType Type of textures used when performing the post process. (default: 0)
  58909. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58910. * @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
  58911. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58912. */
  58913. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58914. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58915. if (defines === void 0) { defines = null; }
  58916. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58917. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58918. if (blockCompilation === void 0) { blockCompilation = false; }
  58919. this.name = name;
  58920. /**
  58921. * Width of the texture to apply the post process on
  58922. */
  58923. this.width = -1;
  58924. /**
  58925. * Height of the texture to apply the post process on
  58926. */
  58927. this.height = -1;
  58928. /**
  58929. * If the buffer needs to be cleared before applying the post process. (default: true)
  58930. * Should be set to false if shader will overwrite all previous pixels.
  58931. */
  58932. this.autoClear = true;
  58933. /**
  58934. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58935. */
  58936. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58937. /**
  58938. * Animations to be used for the post processing
  58939. */
  58940. this.animations = new Array();
  58941. /**
  58942. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58943. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58944. */
  58945. this.enablePixelPerfectMode = false;
  58946. /**
  58947. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58948. */
  58949. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58950. /**
  58951. * Force textures to be a power of two (default: false)
  58952. */
  58953. this.alwaysForcePOT = false;
  58954. /**
  58955. * Number of sample textures (default: 1)
  58956. */
  58957. this.samples = 1;
  58958. /**
  58959. * Modify the scale of the post process to be the same as the viewport (default: false)
  58960. */
  58961. this.adaptScaleToCurrentViewport = false;
  58962. this._reusable = false;
  58963. /**
  58964. * Smart array of input and output textures for the post process.
  58965. */
  58966. this._textures = new BABYLON.SmartArray(2);
  58967. /**
  58968. * The index in _textures that corresponds to the output texture.
  58969. */
  58970. this._currentRenderTextureInd = 0;
  58971. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58972. this._texelSize = BABYLON.Vector2.Zero();
  58973. // Events
  58974. /**
  58975. * An event triggered when the postprocess is activated.
  58976. * @type {BABYLON.Observable}
  58977. */
  58978. this.onActivateObservable = new BABYLON.Observable();
  58979. /**
  58980. * An event triggered when the postprocess changes its size.
  58981. * @type {BABYLON.Observable}
  58982. */
  58983. this.onSizeChangedObservable = new BABYLON.Observable();
  58984. /**
  58985. * An event triggered when the postprocess applies its effect.
  58986. * @type {BABYLON.Observable}
  58987. */
  58988. this.onApplyObservable = new BABYLON.Observable();
  58989. /**
  58990. * An event triggered before rendering the postprocess
  58991. * @type {BABYLON.Observable}
  58992. */
  58993. this.onBeforeRenderObservable = new BABYLON.Observable();
  58994. /**
  58995. * An event triggered after rendering the postprocess
  58996. * @type {BABYLON.Observable}
  58997. */
  58998. this.onAfterRenderObservable = new BABYLON.Observable();
  58999. if (camera != null) {
  59000. this._camera = camera;
  59001. this._scene = camera.getScene();
  59002. camera.attachPostProcess(this);
  59003. this._engine = this._scene.getEngine();
  59004. this._scene.postProcesses.push(this);
  59005. }
  59006. else if (engine) {
  59007. this._engine = engine;
  59008. this._engine.postProcesses.push(this);
  59009. }
  59010. this._options = options;
  59011. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59012. this._reusable = reusable || false;
  59013. this._textureType = textureType;
  59014. this._samplers = samplers || [];
  59015. this._samplers.push("textureSampler");
  59016. this._fragmentUrl = fragmentUrl;
  59017. this._vertexUrl = vertexUrl;
  59018. this._parameters = parameters || [];
  59019. this._parameters.push("scale");
  59020. this._indexParameters = indexParameters;
  59021. if (!blockCompilation) {
  59022. this.updateEffect(defines);
  59023. }
  59024. }
  59025. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59026. /**
  59027. * A function that is added to the onActivateObservable
  59028. */
  59029. set: function (callback) {
  59030. if (this._onActivateObserver) {
  59031. this.onActivateObservable.remove(this._onActivateObserver);
  59032. }
  59033. if (callback) {
  59034. this._onActivateObserver = this.onActivateObservable.add(callback);
  59035. }
  59036. },
  59037. enumerable: true,
  59038. configurable: true
  59039. });
  59040. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59041. /**
  59042. * A function that is added to the onSizeChangedObservable
  59043. */
  59044. set: function (callback) {
  59045. if (this._onSizeChangedObserver) {
  59046. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59047. }
  59048. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59049. },
  59050. enumerable: true,
  59051. configurable: true
  59052. });
  59053. Object.defineProperty(PostProcess.prototype, "onApply", {
  59054. /**
  59055. * A function that is added to the onApplyObservable
  59056. */
  59057. set: function (callback) {
  59058. if (this._onApplyObserver) {
  59059. this.onApplyObservable.remove(this._onApplyObserver);
  59060. }
  59061. this._onApplyObserver = this.onApplyObservable.add(callback);
  59062. },
  59063. enumerable: true,
  59064. configurable: true
  59065. });
  59066. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59067. /**
  59068. * A function that is added to the onBeforeRenderObservable
  59069. */
  59070. set: function (callback) {
  59071. if (this._onBeforeRenderObserver) {
  59072. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59073. }
  59074. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59075. },
  59076. enumerable: true,
  59077. configurable: true
  59078. });
  59079. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59080. /**
  59081. * A function that is added to the onAfterRenderObservable
  59082. */
  59083. set: function (callback) {
  59084. if (this._onAfterRenderObserver) {
  59085. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59086. }
  59087. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59088. },
  59089. enumerable: true,
  59090. configurable: true
  59091. });
  59092. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59093. /**
  59094. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  59095. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59096. */
  59097. get: function () {
  59098. return this._textures.data[this._currentRenderTextureInd];
  59099. },
  59100. set: function (value) {
  59101. this._forcedOutputTexture = value;
  59102. },
  59103. enumerable: true,
  59104. configurable: true
  59105. });
  59106. /**
  59107. * Gets the camera which post process is applied to.
  59108. * @returns The camera the post process is applied to.
  59109. */
  59110. PostProcess.prototype.getCamera = function () {
  59111. return this._camera;
  59112. };
  59113. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59114. /**
  59115. * Gets the texel size of the postprocess.
  59116. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59117. */
  59118. get: function () {
  59119. if (this._shareOutputWithPostProcess) {
  59120. return this._shareOutputWithPostProcess.texelSize;
  59121. }
  59122. if (this._forcedOutputTexture) {
  59123. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59124. }
  59125. return this._texelSize;
  59126. },
  59127. enumerable: true,
  59128. configurable: true
  59129. });
  59130. /**
  59131. * Gets the engine which this post process belongs to.
  59132. * @returns The engine the post process was enabled with.
  59133. */
  59134. PostProcess.prototype.getEngine = function () {
  59135. return this._engine;
  59136. };
  59137. /**
  59138. * The effect that is created when initializing the post process.
  59139. * @returns The created effect corrisponding the the postprocess.
  59140. */
  59141. PostProcess.prototype.getEffect = function () {
  59142. return this._effect;
  59143. };
  59144. /**
  59145. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59146. * @param postProcess The post process to share the output with.
  59147. * @returns This post process.
  59148. */
  59149. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59150. this._disposeTextures();
  59151. this._shareOutputWithPostProcess = postProcess;
  59152. return this;
  59153. };
  59154. /**
  59155. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59156. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59157. */
  59158. PostProcess.prototype.useOwnOutput = function () {
  59159. if (this._textures.length == 0) {
  59160. this._textures = new BABYLON.SmartArray(2);
  59161. }
  59162. this._shareOutputWithPostProcess = null;
  59163. };
  59164. /**
  59165. * Updates the effect with the current post process compile time values and recompiles the shader.
  59166. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59167. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59168. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59169. * @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
  59170. * @param onCompiled Called when the shader has been compiled.
  59171. * @param onError Called if there is an error when compiling a shader.
  59172. */
  59173. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59174. if (defines === void 0) { defines = null; }
  59175. if (uniforms === void 0) { uniforms = null; }
  59176. if (samplers === void 0) { samplers = null; }
  59177. 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);
  59178. };
  59179. /**
  59180. * The post process is reusable if it can be used multiple times within one frame.
  59181. * @returns If the post process is reusable
  59182. */
  59183. PostProcess.prototype.isReusable = function () {
  59184. return this._reusable;
  59185. };
  59186. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59187. PostProcess.prototype.markTextureDirty = function () {
  59188. this.width = -1;
  59189. };
  59190. /**
  59191. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59192. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  59193. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59194. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59195. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59196. */
  59197. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59198. var _this = this;
  59199. if (sourceTexture === void 0) { sourceTexture = null; }
  59200. camera = camera || this._camera;
  59201. var scene = camera.getScene();
  59202. var engine = scene.getEngine();
  59203. var maxSize = engine.getCaps().maxTextureSize;
  59204. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59205. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59206. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  59207. var webVRCamera = camera.parent;
  59208. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59209. requiredWidth /= 2;
  59210. }
  59211. var desiredWidth = (this._options.width || requiredWidth);
  59212. var desiredHeight = this._options.height || requiredHeight;
  59213. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59214. if (this.adaptScaleToCurrentViewport) {
  59215. var currentViewport = engine.currentViewport;
  59216. if (currentViewport) {
  59217. desiredWidth *= currentViewport.width;
  59218. desiredHeight *= currentViewport.height;
  59219. }
  59220. }
  59221. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59222. if (!this._options.width) {
  59223. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59224. }
  59225. if (!this._options.height) {
  59226. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59227. }
  59228. }
  59229. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59230. if (this._textures.length > 0) {
  59231. for (var i = 0; i < this._textures.length; i++) {
  59232. this._engine._releaseTexture(this._textures.data[i]);
  59233. }
  59234. this._textures.reset();
  59235. }
  59236. this.width = desiredWidth;
  59237. this.height = desiredHeight;
  59238. var textureSize = { width: this.width, height: this.height };
  59239. var textureOptions = {
  59240. generateMipMaps: false,
  59241. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59242. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59243. samplingMode: this.renderTargetSamplingMode,
  59244. type: this._textureType
  59245. };
  59246. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59247. if (this._reusable) {
  59248. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59249. }
  59250. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59251. this.onSizeChangedObservable.notifyObservers(this);
  59252. }
  59253. this._textures.forEach(function (texture) {
  59254. if (texture.samples !== _this.samples) {
  59255. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59256. }
  59257. });
  59258. }
  59259. var target;
  59260. if (this._shareOutputWithPostProcess) {
  59261. target = this._shareOutputWithPostProcess.inputTexture;
  59262. }
  59263. else if (this._forcedOutputTexture) {
  59264. target = this._forcedOutputTexture;
  59265. this.width = this._forcedOutputTexture.width;
  59266. this.height = this._forcedOutputTexture.height;
  59267. }
  59268. else {
  59269. target = this.inputTexture;
  59270. }
  59271. // Bind the input of this post process to be used as the output of the previous post process.
  59272. if (this.enablePixelPerfectMode) {
  59273. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59274. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59275. }
  59276. else {
  59277. this._scaleRatio.copyFromFloats(1, 1);
  59278. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59279. }
  59280. this.onActivateObservable.notifyObservers(camera);
  59281. // Clear
  59282. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59283. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59284. }
  59285. if (this._reusable) {
  59286. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59287. }
  59288. };
  59289. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59290. /**
  59291. * If the post process is supported.
  59292. */
  59293. get: function () {
  59294. return this._effect.isSupported;
  59295. },
  59296. enumerable: true,
  59297. configurable: true
  59298. });
  59299. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59300. /**
  59301. * The aspect ratio of the output texture.
  59302. */
  59303. get: function () {
  59304. if (this._shareOutputWithPostProcess) {
  59305. return this._shareOutputWithPostProcess.aspectRatio;
  59306. }
  59307. if (this._forcedOutputTexture) {
  59308. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59309. }
  59310. return this.width / this.height;
  59311. },
  59312. enumerable: true,
  59313. configurable: true
  59314. });
  59315. /**
  59316. * Get a value indicating if the post-process is ready to be used
  59317. * @returns true if the post-process is ready (shader is compiled)
  59318. */
  59319. PostProcess.prototype.isReady = function () {
  59320. return this._effect && this._effect.isReady();
  59321. };
  59322. /**
  59323. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59324. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59325. */
  59326. PostProcess.prototype.apply = function () {
  59327. // Check
  59328. if (!this._effect || !this._effect.isReady())
  59329. return null;
  59330. // States
  59331. this._engine.enableEffect(this._effect);
  59332. this._engine.setState(false);
  59333. this._engine.setDepthBuffer(false);
  59334. this._engine.setDepthWrite(false);
  59335. // Alpha
  59336. this._engine.setAlphaMode(this.alphaMode);
  59337. if (this.alphaConstants) {
  59338. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59339. }
  59340. // Bind the output texture of the preivous post process as the input to this post process.
  59341. var source;
  59342. if (this._shareOutputWithPostProcess) {
  59343. source = this._shareOutputWithPostProcess.inputTexture;
  59344. }
  59345. else if (this._forcedOutputTexture) {
  59346. source = this._forcedOutputTexture;
  59347. }
  59348. else {
  59349. source = this.inputTexture;
  59350. }
  59351. this._effect._bindTexture("textureSampler", source);
  59352. // Parameters
  59353. this._effect.setVector2("scale", this._scaleRatio);
  59354. this.onApplyObservable.notifyObservers(this._effect);
  59355. return this._effect;
  59356. };
  59357. PostProcess.prototype._disposeTextures = function () {
  59358. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59359. return;
  59360. }
  59361. if (this._textures.length > 0) {
  59362. for (var i = 0; i < this._textures.length; i++) {
  59363. this._engine._releaseTexture(this._textures.data[i]);
  59364. }
  59365. }
  59366. this._textures.dispose();
  59367. };
  59368. /**
  59369. * Disposes the post process.
  59370. * @param camera The camera to dispose the post process on.
  59371. */
  59372. PostProcess.prototype.dispose = function (camera) {
  59373. camera = camera || this._camera;
  59374. this._disposeTextures();
  59375. if (this._scene) {
  59376. var index_1 = this._scene.postProcesses.indexOf(this);
  59377. if (index_1 !== -1) {
  59378. this._scene.postProcesses.splice(index_1, 1);
  59379. }
  59380. }
  59381. else {
  59382. var index_2 = this._engine.postProcesses.indexOf(this);
  59383. if (index_2 !== -1) {
  59384. this._engine.postProcesses.splice(index_2, 1);
  59385. }
  59386. }
  59387. if (!camera) {
  59388. return;
  59389. }
  59390. camera.detachPostProcess(this);
  59391. var index = camera._postProcesses.indexOf(this);
  59392. if (index === 0 && camera._postProcesses.length > 0) {
  59393. var firstPostProcess = this._camera._getFirstPostProcess();
  59394. if (firstPostProcess) {
  59395. firstPostProcess.markTextureDirty();
  59396. }
  59397. }
  59398. this.onActivateObservable.clear();
  59399. this.onAfterRenderObservable.clear();
  59400. this.onApplyObservable.clear();
  59401. this.onBeforeRenderObservable.clear();
  59402. this.onSizeChangedObservable.clear();
  59403. };
  59404. return PostProcess;
  59405. }());
  59406. BABYLON.PostProcess = PostProcess;
  59407. })(BABYLON || (BABYLON = {}));
  59408. //# sourceMappingURL=babylon.postProcess.js.map
  59409. var BABYLON;
  59410. (function (BABYLON) {
  59411. var PassPostProcess = /** @class */ (function (_super) {
  59412. __extends(PassPostProcess, _super);
  59413. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  59414. if (camera === void 0) { camera = null; }
  59415. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59416. if (blockCompilation === void 0) { blockCompilation = false; }
  59417. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  59418. }
  59419. return PassPostProcess;
  59420. }(BABYLON.PostProcess));
  59421. BABYLON.PassPostProcess = PassPostProcess;
  59422. })(BABYLON || (BABYLON = {}));
  59423. //# sourceMappingURL=babylon.passPostProcess.js.map
  59424. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59425. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59426. s = arguments[i];
  59427. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59428. t[p] = s[p];
  59429. }
  59430. return t;
  59431. };
  59432. var BABYLON;
  59433. (function (BABYLON) {
  59434. /**
  59435. * Default implementation of @see IShadowGenerator.
  59436. * This is the main object responsible of generating shadows in the framework.
  59437. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59438. */
  59439. var ShadowGenerator = /** @class */ (function () {
  59440. /**
  59441. * Creates a ShadowGenerator object.
  59442. * A ShadowGenerator is the required tool to use the shadows.
  59443. * Each light casting shadows needs to use its own ShadowGenerator.
  59444. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59445. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59446. * @param light The light object generating the shadows.
  59447. * @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.
  59448. */
  59449. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59450. this._bias = 0.00005;
  59451. this._blurBoxOffset = 1;
  59452. this._blurScale = 2;
  59453. this._blurKernel = 1;
  59454. this._useKernelBlur = false;
  59455. this._filter = ShadowGenerator.FILTER_NONE;
  59456. this._darkness = 0;
  59457. this._transparencyShadow = false;
  59458. /**
  59459. * Controls the extent to which the shadows fade out at the edge of the frustum
  59460. * Used only by directionals and spots
  59461. */
  59462. this.frustumEdgeFalloff = 0;
  59463. /**
  59464. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59465. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59466. * It might on the other hand introduce peter panning.
  59467. */
  59468. this.forceBackFacesOnly = false;
  59469. this._lightDirection = BABYLON.Vector3.Zero();
  59470. this._viewMatrix = BABYLON.Matrix.Zero();
  59471. this._projectionMatrix = BABYLON.Matrix.Zero();
  59472. this._transformMatrix = BABYLON.Matrix.Zero();
  59473. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59474. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59475. this._currentFaceIndex = 0;
  59476. this._currentFaceIndexCache = 0;
  59477. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59478. this._mapSize = mapSize;
  59479. this._light = light;
  59480. this._scene = light.getScene();
  59481. light._shadowGenerator = this;
  59482. // Texture type fallback from float to int if not supported.
  59483. var caps = this._scene.getEngine().getCaps();
  59484. if (!useFullFloatFirst) {
  59485. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59486. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59487. }
  59488. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59489. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59490. }
  59491. else {
  59492. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59493. }
  59494. }
  59495. else {
  59496. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59497. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59498. }
  59499. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59500. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59501. }
  59502. else {
  59503. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59504. }
  59505. }
  59506. this._initializeGenerator();
  59507. }
  59508. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59509. /**
  59510. * Shadow generator mode None: no filtering applied.
  59511. */
  59512. get: function () {
  59513. return ShadowGenerator._FILTER_NONE;
  59514. },
  59515. enumerable: true,
  59516. configurable: true
  59517. });
  59518. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59519. /**
  59520. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59521. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59522. */
  59523. get: function () {
  59524. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59525. },
  59526. enumerable: true,
  59527. configurable: true
  59528. });
  59529. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59530. /**
  59531. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59532. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59533. */
  59534. get: function () {
  59535. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59536. },
  59537. enumerable: true,
  59538. configurable: true
  59539. });
  59540. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59541. /**
  59542. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59543. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59544. */
  59545. get: function () {
  59546. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59547. },
  59548. enumerable: true,
  59549. configurable: true
  59550. });
  59551. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59552. /**
  59553. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59554. * edge artifacts on steep falloff.
  59555. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59556. */
  59557. get: function () {
  59558. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59559. },
  59560. enumerable: true,
  59561. configurable: true
  59562. });
  59563. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59564. /**
  59565. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59566. * edge artifacts on steep falloff.
  59567. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59568. */
  59569. get: function () {
  59570. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59571. },
  59572. enumerable: true,
  59573. configurable: true
  59574. });
  59575. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59576. /**
  59577. * Gets the bias: offset applied on the depth preventing acnea.
  59578. */
  59579. get: function () {
  59580. return this._bias;
  59581. },
  59582. /**
  59583. * Sets the bias: offset applied on the depth preventing acnea.
  59584. */
  59585. set: function (bias) {
  59586. this._bias = bias;
  59587. },
  59588. enumerable: true,
  59589. configurable: true
  59590. });
  59591. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59592. /**
  59593. * Gets the blur box offset: offset applied during the blur pass.
  59594. * Only usefull if useKernelBlur = false
  59595. */
  59596. get: function () {
  59597. return this._blurBoxOffset;
  59598. },
  59599. /**
  59600. * Sets the blur box offset: offset applied during the blur pass.
  59601. * Only usefull if useKernelBlur = false
  59602. */
  59603. set: function (value) {
  59604. if (this._blurBoxOffset === value) {
  59605. return;
  59606. }
  59607. this._blurBoxOffset = value;
  59608. this._disposeBlurPostProcesses();
  59609. },
  59610. enumerable: true,
  59611. configurable: true
  59612. });
  59613. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59614. /**
  59615. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59616. * 2 means half of the size.
  59617. */
  59618. get: function () {
  59619. return this._blurScale;
  59620. },
  59621. /**
  59622. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59623. * 2 means half of the size.
  59624. */
  59625. set: function (value) {
  59626. if (this._blurScale === value) {
  59627. return;
  59628. }
  59629. this._blurScale = value;
  59630. this._disposeBlurPostProcesses();
  59631. },
  59632. enumerable: true,
  59633. configurable: true
  59634. });
  59635. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59636. /**
  59637. * Gets the blur kernel: kernel size of the blur pass.
  59638. * Only usefull if useKernelBlur = true
  59639. */
  59640. get: function () {
  59641. return this._blurKernel;
  59642. },
  59643. /**
  59644. * Sets the blur kernel: kernel size of the blur pass.
  59645. * Only usefull if useKernelBlur = true
  59646. */
  59647. set: function (value) {
  59648. if (this._blurKernel === value) {
  59649. return;
  59650. }
  59651. this._blurKernel = value;
  59652. this._disposeBlurPostProcesses();
  59653. },
  59654. enumerable: true,
  59655. configurable: true
  59656. });
  59657. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59658. /**
  59659. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59660. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59661. */
  59662. get: function () {
  59663. return this._useKernelBlur;
  59664. },
  59665. /**
  59666. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59667. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59668. */
  59669. set: function (value) {
  59670. if (this._useKernelBlur === value) {
  59671. return;
  59672. }
  59673. this._useKernelBlur = value;
  59674. this._disposeBlurPostProcesses();
  59675. },
  59676. enumerable: true,
  59677. configurable: true
  59678. });
  59679. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59680. /**
  59681. * Gets the depth scale used in ESM mode.
  59682. */
  59683. get: function () {
  59684. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59685. },
  59686. /**
  59687. * Sets the depth scale used in ESM mode.
  59688. * This can override the scale stored on the light.
  59689. */
  59690. set: function (value) {
  59691. this._depthScale = value;
  59692. },
  59693. enumerable: true,
  59694. configurable: true
  59695. });
  59696. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59697. /**
  59698. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59699. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59700. */
  59701. get: function () {
  59702. return this._filter;
  59703. },
  59704. /**
  59705. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59706. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59707. */
  59708. set: function (value) {
  59709. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59710. if (this._light.needCube()) {
  59711. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59712. this.useExponentialShadowMap = true;
  59713. return;
  59714. }
  59715. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59716. this.useCloseExponentialShadowMap = true;
  59717. return;
  59718. }
  59719. }
  59720. if (this._filter === value) {
  59721. return;
  59722. }
  59723. this._filter = value;
  59724. this._disposeBlurPostProcesses();
  59725. this._applyFilterValues();
  59726. this._light._markMeshesAsLightDirty();
  59727. },
  59728. enumerable: true,
  59729. configurable: true
  59730. });
  59731. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59732. /**
  59733. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59734. */
  59735. get: function () {
  59736. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59737. },
  59738. /**
  59739. * Sets the current filter to Poisson Sampling aka PCF.
  59740. */
  59741. set: function (value) {
  59742. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59743. return;
  59744. }
  59745. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59746. },
  59747. enumerable: true,
  59748. configurable: true
  59749. });
  59750. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59751. /**
  59752. * Gets if the current filter is set to VSM.
  59753. * DEPRECATED. Should use useExponentialShadowMap instead.
  59754. */
  59755. get: function () {
  59756. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59757. return this.useExponentialShadowMap;
  59758. },
  59759. /**
  59760. * Sets the current filter is to VSM.
  59761. * DEPRECATED. Should use useExponentialShadowMap instead.
  59762. */
  59763. set: function (value) {
  59764. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59765. this.useExponentialShadowMap = value;
  59766. },
  59767. enumerable: true,
  59768. configurable: true
  59769. });
  59770. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59771. /**
  59772. * Gets if the current filter is set to blurred VSM.
  59773. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59774. */
  59775. get: function () {
  59776. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59777. return this.useBlurExponentialShadowMap;
  59778. },
  59779. /**
  59780. * Sets the current filter is to blurred VSM.
  59781. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59782. */
  59783. set: function (value) {
  59784. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59785. this.useBlurExponentialShadowMap = value;
  59786. },
  59787. enumerable: true,
  59788. configurable: true
  59789. });
  59790. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59791. /**
  59792. * Gets if the current filter is set to ESM.
  59793. */
  59794. get: function () {
  59795. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59796. },
  59797. /**
  59798. * Sets the current filter is to ESM.
  59799. */
  59800. set: function (value) {
  59801. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59802. return;
  59803. }
  59804. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59805. },
  59806. enumerable: true,
  59807. configurable: true
  59808. });
  59809. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59810. /**
  59811. * Gets if the current filter is set to filtered ESM.
  59812. */
  59813. get: function () {
  59814. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59815. },
  59816. /**
  59817. * Gets if the current filter is set to filtered ESM.
  59818. */
  59819. set: function (value) {
  59820. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59821. return;
  59822. }
  59823. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59824. },
  59825. enumerable: true,
  59826. configurable: true
  59827. });
  59828. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59829. /**
  59830. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59831. * exponential to prevent steep falloff artifacts).
  59832. */
  59833. get: function () {
  59834. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59835. },
  59836. /**
  59837. * Sets the current filter to "close ESM" (using the inverse of the
  59838. * exponential to prevent steep falloff artifacts).
  59839. */
  59840. set: function (value) {
  59841. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59842. return;
  59843. }
  59844. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59845. },
  59846. enumerable: true,
  59847. configurable: true
  59848. });
  59849. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59850. /**
  59851. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59852. * exponential to prevent steep falloff artifacts).
  59853. */
  59854. get: function () {
  59855. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59856. },
  59857. /**
  59858. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59859. * exponential to prevent steep falloff artifacts).
  59860. */
  59861. set: function (value) {
  59862. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59863. return;
  59864. }
  59865. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59866. },
  59867. enumerable: true,
  59868. configurable: true
  59869. });
  59870. /**
  59871. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59872. * 0 means strongest and 1 would means no shadow.
  59873. * @returns the darkness.
  59874. */
  59875. ShadowGenerator.prototype.getDarkness = function () {
  59876. return this._darkness;
  59877. };
  59878. /**
  59879. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59880. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59881. * @returns the shadow generator allowing fluent coding.
  59882. */
  59883. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59884. if (darkness >= 1.0)
  59885. this._darkness = 1.0;
  59886. else if (darkness <= 0.0)
  59887. this._darkness = 0.0;
  59888. else
  59889. this._darkness = darkness;
  59890. return this;
  59891. };
  59892. /**
  59893. * Sets the ability to have transparent shadow (boolean).
  59894. * @param transparent True if transparent else False
  59895. * @returns the shadow generator allowing fluent coding
  59896. */
  59897. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59898. this._transparencyShadow = transparent;
  59899. return this;
  59900. };
  59901. /**
  59902. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59903. * @returns The render target texture if present otherwise, null
  59904. */
  59905. ShadowGenerator.prototype.getShadowMap = function () {
  59906. return this._shadowMap;
  59907. };
  59908. /**
  59909. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59910. * @returns The render target texture if the shadow map is present otherwise, null
  59911. */
  59912. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59913. if (this._shadowMap2) {
  59914. return this._shadowMap2;
  59915. }
  59916. return this._shadowMap;
  59917. };
  59918. /**
  59919. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59920. * @param mesh Mesh to add
  59921. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59922. * @returns the Shadow Generator itself
  59923. */
  59924. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59925. if (includeDescendants === void 0) { includeDescendants = true; }
  59926. if (!this._shadowMap) {
  59927. return this;
  59928. }
  59929. if (!this._shadowMap.renderList) {
  59930. this._shadowMap.renderList = [];
  59931. }
  59932. this._shadowMap.renderList.push(mesh);
  59933. if (includeDescendants) {
  59934. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59935. }
  59936. return this;
  59937. var _a;
  59938. };
  59939. /**
  59940. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59941. * @param mesh Mesh to remove
  59942. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59943. * @returns the Shadow Generator itself
  59944. */
  59945. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59946. if (includeDescendants === void 0) { includeDescendants = true; }
  59947. if (!this._shadowMap || !this._shadowMap.renderList) {
  59948. return this;
  59949. }
  59950. var index = this._shadowMap.renderList.indexOf(mesh);
  59951. if (index !== -1) {
  59952. this._shadowMap.renderList.splice(index, 1);
  59953. }
  59954. if (includeDescendants) {
  59955. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59956. var child = _a[_i];
  59957. this.removeShadowCaster(child);
  59958. }
  59959. }
  59960. return this;
  59961. };
  59962. /**
  59963. * Returns the associated light object.
  59964. * @returns the light generating the shadow
  59965. */
  59966. ShadowGenerator.prototype.getLight = function () {
  59967. return this._light;
  59968. };
  59969. ShadowGenerator.prototype._initializeGenerator = function () {
  59970. this._light._markMeshesAsLightDirty();
  59971. this._initializeShadowMap();
  59972. };
  59973. ShadowGenerator.prototype._initializeShadowMap = function () {
  59974. var _this = this;
  59975. // Render target
  59976. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59977. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59978. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59979. this._shadowMap.anisotropicFilteringLevel = 1;
  59980. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59981. this._shadowMap.renderParticles = false;
  59982. this._shadowMap.ignoreCameraViewport = true;
  59983. // Record Face Index before render.
  59984. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59985. _this._currentFaceIndex = faceIndex;
  59986. });
  59987. // Custom render function.
  59988. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59989. // Blur if required afer render.
  59990. this._shadowMap.onAfterUnbindObservable.add(function () {
  59991. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59992. return;
  59993. }
  59994. var shadowMap = _this.getShadowMapForRendering();
  59995. if (shadowMap) {
  59996. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59997. }
  59998. });
  59999. // Clear according to the chosen filter.
  60000. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60001. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60002. this._shadowMap.onClearObservable.add(function (engine) {
  60003. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60004. engine.clear(zero, true, true, true);
  60005. }
  60006. else {
  60007. engine.clear(one, true, true, true);
  60008. }
  60009. });
  60010. };
  60011. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60012. var _this = this;
  60013. var engine = this._scene.getEngine();
  60014. var targetSize = this._mapSize / this.blurScale;
  60015. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60016. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60017. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60018. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60019. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60020. }
  60021. if (this.useKernelBlur) {
  60022. 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);
  60023. this._kernelBlurXPostprocess.width = targetSize;
  60024. this._kernelBlurXPostprocess.height = targetSize;
  60025. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60026. effect.setTexture("textureSampler", _this._shadowMap);
  60027. });
  60028. 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);
  60029. this._kernelBlurXPostprocess.autoClear = false;
  60030. this._kernelBlurYPostprocess.autoClear = false;
  60031. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60032. this._kernelBlurXPostprocess.packedFloat = true;
  60033. this._kernelBlurYPostprocess.packedFloat = true;
  60034. }
  60035. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60036. }
  60037. else {
  60038. 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);
  60039. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60040. effect.setFloat2("screenSize", targetSize, targetSize);
  60041. effect.setTexture("textureSampler", _this._shadowMap);
  60042. });
  60043. this._boxBlurPostprocess.autoClear = false;
  60044. this._blurPostProcesses = [this._boxBlurPostprocess];
  60045. }
  60046. };
  60047. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60048. var index;
  60049. var engine = this._scene.getEngine();
  60050. if (depthOnlySubMeshes.length) {
  60051. engine.setColorWrite(false);
  60052. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60053. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60054. }
  60055. engine.setColorWrite(true);
  60056. }
  60057. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60058. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60059. }
  60060. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60061. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60062. }
  60063. if (this._transparencyShadow) {
  60064. for (index = 0; index < transparentSubMeshes.length; index++) {
  60065. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60066. }
  60067. }
  60068. };
  60069. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60070. var _this = this;
  60071. var mesh = subMesh.getRenderingMesh();
  60072. var scene = this._scene;
  60073. var engine = scene.getEngine();
  60074. var material = subMesh.getMaterial();
  60075. if (!material) {
  60076. return;
  60077. }
  60078. // Culling
  60079. engine.setState(material.backFaceCulling);
  60080. // Managing instances
  60081. var batch = mesh._getInstancesRenderList(subMesh._id);
  60082. if (batch.mustReturn) {
  60083. return;
  60084. }
  60085. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60086. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60087. engine.enableEffect(this._effect);
  60088. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60089. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60090. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60091. this._effect.setVector3("lightPosition", this.getLight().position);
  60092. if (scene.activeCamera) {
  60093. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60094. }
  60095. // Alpha test
  60096. if (material && material.needAlphaTesting()) {
  60097. var alphaTexture = material.getAlphaTestTexture();
  60098. if (alphaTexture) {
  60099. this._effect.setTexture("diffuseSampler", alphaTexture);
  60100. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60101. }
  60102. }
  60103. // Bones
  60104. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60105. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60106. }
  60107. if (this.forceBackFacesOnly) {
  60108. engine.setState(true, 0, false, true);
  60109. }
  60110. // Draw
  60111. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60112. if (this.forceBackFacesOnly) {
  60113. engine.setState(true, 0, false, false);
  60114. }
  60115. }
  60116. else {
  60117. // Need to reset refresh rate of the shadowMap
  60118. if (this._shadowMap) {
  60119. this._shadowMap.resetRefreshCounter();
  60120. }
  60121. }
  60122. };
  60123. ShadowGenerator.prototype._applyFilterValues = function () {
  60124. if (!this._shadowMap) {
  60125. return;
  60126. }
  60127. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60128. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60129. }
  60130. else {
  60131. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60132. }
  60133. };
  60134. /**
  60135. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60136. * @param onCompiled Callback triggered at the and of the effects compilation
  60137. * @param options Sets of optional options forcing the compilation with different modes
  60138. */
  60139. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60140. var _this = this;
  60141. var localOptions = __assign({ useInstances: false }, options);
  60142. var shadowMap = this.getShadowMap();
  60143. if (!shadowMap) {
  60144. if (onCompiled) {
  60145. onCompiled(this);
  60146. }
  60147. return;
  60148. }
  60149. var renderList = shadowMap.renderList;
  60150. if (!renderList) {
  60151. if (onCompiled) {
  60152. onCompiled(this);
  60153. }
  60154. return;
  60155. }
  60156. var subMeshes = new Array();
  60157. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60158. var mesh = renderList_1[_i];
  60159. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60160. }
  60161. if (subMeshes.length === 0) {
  60162. if (onCompiled) {
  60163. onCompiled(this);
  60164. }
  60165. return;
  60166. }
  60167. var currentIndex = 0;
  60168. var checkReady = function () {
  60169. if (!_this._scene || !_this._scene.getEngine()) {
  60170. return;
  60171. }
  60172. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60173. currentIndex++;
  60174. if (currentIndex >= subMeshes.length) {
  60175. if (onCompiled) {
  60176. onCompiled(_this);
  60177. }
  60178. return;
  60179. }
  60180. }
  60181. setTimeout(checkReady, 16);
  60182. };
  60183. checkReady();
  60184. };
  60185. /**
  60186. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60187. * @param options Sets of optional options forcing the compilation with different modes
  60188. * @returns A promise that resolves when the compilation completes
  60189. */
  60190. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60191. var _this = this;
  60192. return new Promise(function (resolve) {
  60193. _this.forceCompilation(function () {
  60194. resolve();
  60195. }, options);
  60196. });
  60197. };
  60198. /**
  60199. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60200. * @param subMesh The submesh we want to render in the shadow map
  60201. * @param useInstances Defines wether will draw in the map using instances
  60202. * @returns true if ready otherwise, false
  60203. */
  60204. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60205. var defines = [];
  60206. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60207. defines.push("#define FLOAT");
  60208. }
  60209. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60210. defines.push("#define ESM");
  60211. }
  60212. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60213. var mesh = subMesh.getMesh();
  60214. var material = subMesh.getMaterial();
  60215. // Alpha test
  60216. if (material && material.needAlphaTesting()) {
  60217. var alphaTexture = material.getAlphaTestTexture();
  60218. if (alphaTexture) {
  60219. defines.push("#define ALPHATEST");
  60220. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60221. attribs.push(BABYLON.VertexBuffer.UVKind);
  60222. defines.push("#define UV1");
  60223. }
  60224. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60225. if (alphaTexture.coordinatesIndex === 1) {
  60226. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60227. defines.push("#define UV2");
  60228. }
  60229. }
  60230. }
  60231. }
  60232. // Bones
  60233. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60234. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60235. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60236. if (mesh.numBoneInfluencers > 4) {
  60237. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60238. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60239. }
  60240. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60241. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60242. }
  60243. else {
  60244. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60245. }
  60246. // Instances
  60247. if (useInstances) {
  60248. defines.push("#define INSTANCES");
  60249. attribs.push("world0");
  60250. attribs.push("world1");
  60251. attribs.push("world2");
  60252. attribs.push("world3");
  60253. }
  60254. // Get correct effect
  60255. var join = defines.join("\n");
  60256. if (this._cachedDefines !== join) {
  60257. this._cachedDefines = join;
  60258. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60259. }
  60260. if (!this._effect.isReady()) {
  60261. return false;
  60262. }
  60263. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60264. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60265. this._initializeBlurRTTAndPostProcesses();
  60266. }
  60267. }
  60268. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60269. return false;
  60270. }
  60271. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60272. return false;
  60273. }
  60274. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60275. return false;
  60276. }
  60277. return true;
  60278. };
  60279. /**
  60280. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60281. * @param defines Defines of the material we want to update
  60282. * @param lightIndex Index of the light in the enabled light list of the material
  60283. */
  60284. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60285. var scene = this._scene;
  60286. var light = this._light;
  60287. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60288. return;
  60289. }
  60290. defines["SHADOW" + lightIndex] = true;
  60291. if (this.usePoissonSampling) {
  60292. defines["SHADOWPCF" + lightIndex] = true;
  60293. }
  60294. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60295. defines["SHADOWESM" + lightIndex] = true;
  60296. }
  60297. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60298. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60299. }
  60300. if (light.needCube()) {
  60301. defines["SHADOWCUBE" + lightIndex] = true;
  60302. }
  60303. };
  60304. /**
  60305. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60306. * defined in the generator but impacting the effect).
  60307. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60308. * @param effect The effect we are binfing the information for
  60309. */
  60310. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60311. var light = this._light;
  60312. var scene = this._scene;
  60313. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60314. return;
  60315. }
  60316. var camera = scene.activeCamera;
  60317. if (!camera) {
  60318. return;
  60319. }
  60320. var shadowMap = this.getShadowMap();
  60321. if (!shadowMap) {
  60322. return;
  60323. }
  60324. if (!light.needCube()) {
  60325. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60326. }
  60327. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60328. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60329. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60330. };
  60331. /**
  60332. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60333. * (eq to shadow prjection matrix * light transform matrix)
  60334. * @returns The transform matrix used to create the shadow map
  60335. */
  60336. ShadowGenerator.prototype.getTransformMatrix = function () {
  60337. var scene = this._scene;
  60338. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60339. return this._transformMatrix;
  60340. }
  60341. this._currentRenderID = scene.getRenderId();
  60342. this._currentFaceIndexCache = this._currentFaceIndex;
  60343. var lightPosition = this._light.position;
  60344. if (this._light.computeTransformedInformation()) {
  60345. lightPosition = this._light.transformedPosition;
  60346. }
  60347. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60348. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60349. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60350. }
  60351. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60352. this._cachedPosition.copyFrom(lightPosition);
  60353. this._cachedDirection.copyFrom(this._lightDirection);
  60354. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60355. var shadowMap = this.getShadowMap();
  60356. if (shadowMap) {
  60357. var renderList = shadowMap.renderList;
  60358. if (renderList) {
  60359. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60360. }
  60361. }
  60362. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60363. }
  60364. return this._transformMatrix;
  60365. };
  60366. /**
  60367. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60368. * Cube and 2D textures for instance.
  60369. */
  60370. ShadowGenerator.prototype.recreateShadowMap = function () {
  60371. var shadowMap = this._shadowMap;
  60372. if (!shadowMap) {
  60373. return;
  60374. }
  60375. // Track render list.
  60376. var renderList = shadowMap.renderList;
  60377. // Clean up existing data.
  60378. this._disposeRTTandPostProcesses();
  60379. // Reinitializes.
  60380. this._initializeGenerator();
  60381. // Reaffect the filter to ensure a correct fallback if necessary.
  60382. this.filter = this.filter;
  60383. // Reaffect the filter.
  60384. this._applyFilterValues();
  60385. // Reaffect Render List.
  60386. this._shadowMap.renderList = renderList;
  60387. };
  60388. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60389. if (this._shadowMap2) {
  60390. this._shadowMap2.dispose();
  60391. this._shadowMap2 = null;
  60392. }
  60393. if (this._boxBlurPostprocess) {
  60394. this._boxBlurPostprocess.dispose();
  60395. this._boxBlurPostprocess = null;
  60396. }
  60397. if (this._kernelBlurXPostprocess) {
  60398. this._kernelBlurXPostprocess.dispose();
  60399. this._kernelBlurXPostprocess = null;
  60400. }
  60401. if (this._kernelBlurYPostprocess) {
  60402. this._kernelBlurYPostprocess.dispose();
  60403. this._kernelBlurYPostprocess = null;
  60404. }
  60405. this._blurPostProcesses = [];
  60406. };
  60407. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60408. if (this._shadowMap) {
  60409. this._shadowMap.dispose();
  60410. this._shadowMap = null;
  60411. }
  60412. this._disposeBlurPostProcesses();
  60413. };
  60414. /**
  60415. * Disposes the ShadowGenerator.
  60416. * Returns nothing.
  60417. */
  60418. ShadowGenerator.prototype.dispose = function () {
  60419. this._disposeRTTandPostProcesses();
  60420. if (this._light) {
  60421. this._light._shadowGenerator = null;
  60422. this._light._markMeshesAsLightDirty();
  60423. }
  60424. };
  60425. /**
  60426. * Serializes the shadow generator setup to a json object.
  60427. * @returns The serialized JSON object
  60428. */
  60429. ShadowGenerator.prototype.serialize = function () {
  60430. var serializationObject = {};
  60431. var shadowMap = this.getShadowMap();
  60432. if (!shadowMap) {
  60433. return serializationObject;
  60434. }
  60435. serializationObject.lightId = this._light.id;
  60436. serializationObject.mapSize = shadowMap.getRenderSize();
  60437. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60438. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60439. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60440. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60441. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60442. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60443. serializationObject.depthScale = this.depthScale;
  60444. serializationObject.darkness = this.getDarkness();
  60445. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60446. serializationObject.blurKernel = this.blurKernel;
  60447. serializationObject.blurScale = this.blurScale;
  60448. serializationObject.useKernelBlur = this.useKernelBlur;
  60449. serializationObject.transparencyShadow = this._transparencyShadow;
  60450. serializationObject.renderList = [];
  60451. if (shadowMap.renderList) {
  60452. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60453. var mesh = shadowMap.renderList[meshIndex];
  60454. serializationObject.renderList.push(mesh.id);
  60455. }
  60456. }
  60457. return serializationObject;
  60458. };
  60459. /**
  60460. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60461. * @param parsedShadowGenerator The JSON object to parse
  60462. * @param scene The scene to create the shadow map for
  60463. * @returns The parsed shadow generator
  60464. */
  60465. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60466. //casting to point light, as light is missing the position attr and typescript complains.
  60467. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60468. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60469. var shadowMap = shadowGenerator.getShadowMap();
  60470. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60471. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60472. meshes.forEach(function (mesh) {
  60473. if (!shadowMap) {
  60474. return;
  60475. }
  60476. if (!shadowMap.renderList) {
  60477. shadowMap.renderList = [];
  60478. }
  60479. shadowMap.renderList.push(mesh);
  60480. });
  60481. }
  60482. if (parsedShadowGenerator.usePoissonSampling) {
  60483. shadowGenerator.usePoissonSampling = true;
  60484. }
  60485. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60486. shadowGenerator.useExponentialShadowMap = true;
  60487. }
  60488. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60489. shadowGenerator.useBlurExponentialShadowMap = true;
  60490. }
  60491. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60492. shadowGenerator.useCloseExponentialShadowMap = true;
  60493. }
  60494. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60495. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60496. }
  60497. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60498. shadowGenerator.useExponentialShadowMap = true;
  60499. }
  60500. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60501. shadowGenerator.useBlurExponentialShadowMap = true;
  60502. }
  60503. if (parsedShadowGenerator.depthScale) {
  60504. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60505. }
  60506. if (parsedShadowGenerator.blurScale) {
  60507. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60508. }
  60509. if (parsedShadowGenerator.blurBoxOffset) {
  60510. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60511. }
  60512. if (parsedShadowGenerator.useKernelBlur) {
  60513. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60514. }
  60515. if (parsedShadowGenerator.blurKernel) {
  60516. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60517. }
  60518. if (parsedShadowGenerator.bias !== undefined) {
  60519. shadowGenerator.bias = parsedShadowGenerator.bias;
  60520. }
  60521. if (parsedShadowGenerator.darkness) {
  60522. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60523. }
  60524. if (parsedShadowGenerator.transparencyShadow) {
  60525. shadowGenerator.setTransparencyShadow(true);
  60526. }
  60527. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60528. return shadowGenerator;
  60529. };
  60530. ShadowGenerator._FILTER_NONE = 0;
  60531. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60532. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60533. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60534. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60535. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60536. return ShadowGenerator;
  60537. }());
  60538. BABYLON.ShadowGenerator = ShadowGenerator;
  60539. })(BABYLON || (BABYLON = {}));
  60540. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60541. var BABYLON;
  60542. (function (BABYLON) {
  60543. var DefaultLoadingScreen = /** @class */ (function () {
  60544. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60545. if (_loadingText === void 0) { _loadingText = ""; }
  60546. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60547. var _this = this;
  60548. this._renderingCanvas = _renderingCanvas;
  60549. this._loadingText = _loadingText;
  60550. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60551. // Resize
  60552. this._resizeLoadingUI = function () {
  60553. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60554. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60555. if (!_this._loadingDiv) {
  60556. return;
  60557. }
  60558. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60559. _this._loadingDiv.style.left = canvasRect.left + "px";
  60560. _this._loadingDiv.style.top = canvasRect.top + "px";
  60561. _this._loadingDiv.style.width = canvasRect.width + "px";
  60562. _this._loadingDiv.style.height = canvasRect.height + "px";
  60563. };
  60564. }
  60565. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60566. if (this._loadingDiv) {
  60567. // Do not add a loading screen if there is already one
  60568. return;
  60569. }
  60570. this._loadingDiv = document.createElement("div");
  60571. this._loadingDiv.id = "babylonjsLoadingDiv";
  60572. this._loadingDiv.style.opacity = "0";
  60573. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60574. this._loadingDiv.style.pointerEvents = "none";
  60575. // Loading text
  60576. this._loadingTextDiv = document.createElement("div");
  60577. this._loadingTextDiv.style.position = "absolute";
  60578. this._loadingTextDiv.style.left = "0";
  60579. this._loadingTextDiv.style.top = "50%";
  60580. this._loadingTextDiv.style.marginTop = "80px";
  60581. this._loadingTextDiv.style.width = "100%";
  60582. this._loadingTextDiv.style.height = "20px";
  60583. this._loadingTextDiv.style.fontFamily = "Arial";
  60584. this._loadingTextDiv.style.fontSize = "14px";
  60585. this._loadingTextDiv.style.color = "white";
  60586. this._loadingTextDiv.style.textAlign = "center";
  60587. this._loadingTextDiv.innerHTML = "Loading";
  60588. this._loadingDiv.appendChild(this._loadingTextDiv);
  60589. //set the predefined text
  60590. this._loadingTextDiv.innerHTML = this._loadingText;
  60591. // Generating keyframes
  60592. var style = document.createElement('style');
  60593. style.type = 'text/css';
  60594. 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 }";
  60595. style.innerHTML = keyFrames;
  60596. document.getElementsByTagName('head')[0].appendChild(style);
  60597. // Loading img
  60598. var imgBack = new Image();
  60599. 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";
  60600. imgBack.style.position = "absolute";
  60601. imgBack.style.left = "50%";
  60602. imgBack.style.top = "50%";
  60603. imgBack.style.marginLeft = "-60px";
  60604. imgBack.style.marginTop = "-60px";
  60605. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60606. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60607. imgBack.style.transformOrigin = "50% 50%";
  60608. imgBack.style.webkitTransformOrigin = "50% 50%";
  60609. this._loadingDiv.appendChild(imgBack);
  60610. this._resizeLoadingUI();
  60611. window.addEventListener("resize", this._resizeLoadingUI);
  60612. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60613. document.body.appendChild(this._loadingDiv);
  60614. this._loadingDiv.style.opacity = "1";
  60615. };
  60616. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60617. var _this = this;
  60618. if (!this._loadingDiv) {
  60619. return;
  60620. }
  60621. var onTransitionEnd = function () {
  60622. if (!_this._loadingDiv) {
  60623. return;
  60624. }
  60625. document.body.removeChild(_this._loadingDiv);
  60626. window.removeEventListener("resize", _this._resizeLoadingUI);
  60627. _this._loadingDiv = null;
  60628. };
  60629. this._loadingDiv.style.opacity = "0";
  60630. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60631. };
  60632. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60633. set: function (text) {
  60634. this._loadingText = text;
  60635. if (this._loadingTextDiv) {
  60636. this._loadingTextDiv.innerHTML = this._loadingText;
  60637. }
  60638. },
  60639. enumerable: true,
  60640. configurable: true
  60641. });
  60642. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60643. get: function () {
  60644. return this._loadingDivBackgroundColor;
  60645. },
  60646. set: function (color) {
  60647. this._loadingDivBackgroundColor = color;
  60648. if (!this._loadingDiv) {
  60649. return;
  60650. }
  60651. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60652. },
  60653. enumerable: true,
  60654. configurable: true
  60655. });
  60656. return DefaultLoadingScreen;
  60657. }());
  60658. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60659. })(BABYLON || (BABYLON = {}));
  60660. //# sourceMappingURL=babylon.loadingScreen.js.map
  60661. var BABYLON;
  60662. (function (BABYLON) {
  60663. var SceneLoaderProgressEvent = /** @class */ (function () {
  60664. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60665. this.lengthComputable = lengthComputable;
  60666. this.loaded = loaded;
  60667. this.total = total;
  60668. }
  60669. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60670. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60671. };
  60672. return SceneLoaderProgressEvent;
  60673. }());
  60674. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60675. var SceneLoader = /** @class */ (function () {
  60676. function SceneLoader() {
  60677. }
  60678. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60679. get: function () {
  60680. return 0;
  60681. },
  60682. enumerable: true,
  60683. configurable: true
  60684. });
  60685. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60686. get: function () {
  60687. return 1;
  60688. },
  60689. enumerable: true,
  60690. configurable: true
  60691. });
  60692. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60693. get: function () {
  60694. return 2;
  60695. },
  60696. enumerable: true,
  60697. configurable: true
  60698. });
  60699. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60700. get: function () {
  60701. return 3;
  60702. },
  60703. enumerable: true,
  60704. configurable: true
  60705. });
  60706. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60707. get: function () {
  60708. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60709. },
  60710. set: function (value) {
  60711. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60712. },
  60713. enumerable: true,
  60714. configurable: true
  60715. });
  60716. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60717. get: function () {
  60718. return SceneLoader._ShowLoadingScreen;
  60719. },
  60720. set: function (value) {
  60721. SceneLoader._ShowLoadingScreen = value;
  60722. },
  60723. enumerable: true,
  60724. configurable: true
  60725. });
  60726. Object.defineProperty(SceneLoader, "loggingLevel", {
  60727. get: function () {
  60728. return SceneLoader._loggingLevel;
  60729. },
  60730. set: function (value) {
  60731. SceneLoader._loggingLevel = value;
  60732. },
  60733. enumerable: true,
  60734. configurable: true
  60735. });
  60736. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60737. get: function () {
  60738. return SceneLoader._CleanBoneMatrixWeights;
  60739. },
  60740. set: function (value) {
  60741. SceneLoader._CleanBoneMatrixWeights = value;
  60742. },
  60743. enumerable: true,
  60744. configurable: true
  60745. });
  60746. SceneLoader._getDefaultPlugin = function () {
  60747. return SceneLoader._registeredPlugins[".babylon"];
  60748. };
  60749. SceneLoader._getPluginForExtension = function (extension) {
  60750. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60751. if (registeredPlugin) {
  60752. return registeredPlugin;
  60753. }
  60754. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60755. return SceneLoader._getDefaultPlugin();
  60756. };
  60757. SceneLoader._getPluginForDirectLoad = function (data) {
  60758. for (var extension in SceneLoader._registeredPlugins) {
  60759. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60760. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60761. return SceneLoader._registeredPlugins[extension];
  60762. }
  60763. }
  60764. return SceneLoader._getDefaultPlugin();
  60765. };
  60766. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60767. if (sceneFilename.name) {
  60768. sceneFilename = sceneFilename.name;
  60769. }
  60770. var queryStringPosition = sceneFilename.indexOf("?");
  60771. if (queryStringPosition !== -1) {
  60772. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60773. }
  60774. var dotPosition = sceneFilename.lastIndexOf(".");
  60775. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60776. return SceneLoader._getPluginForExtension(extension);
  60777. };
  60778. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60779. SceneLoader._getDirectLoad = function (sceneFilename) {
  60780. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60781. return sceneFilename.substr(5);
  60782. }
  60783. return null;
  60784. };
  60785. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60786. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60787. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60788. var plugin;
  60789. if (registeredPlugin.plugin.createPlugin) {
  60790. plugin = registeredPlugin.plugin.createPlugin();
  60791. }
  60792. else {
  60793. plugin = registeredPlugin.plugin;
  60794. }
  60795. var useArrayBuffer = registeredPlugin.isBinary;
  60796. var database;
  60797. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60798. var dataCallback = function (data, responseURL) {
  60799. if (scene.isDisposed) {
  60800. onError("Scene has been disposed");
  60801. return;
  60802. }
  60803. scene.database = database;
  60804. onSuccess(plugin, data, responseURL);
  60805. };
  60806. var request = null;
  60807. var pluginDisposed = false;
  60808. var onDisposeObservable = plugin.onDisposeObservable;
  60809. if (onDisposeObservable) {
  60810. onDisposeObservable.add(function () {
  60811. pluginDisposed = true;
  60812. if (request) {
  60813. request.abort();
  60814. request = null;
  60815. }
  60816. onDispose();
  60817. });
  60818. }
  60819. var manifestChecked = function () {
  60820. if (pluginDisposed) {
  60821. return;
  60822. }
  60823. var url = rootUrl + sceneFilename;
  60824. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60825. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60826. } : undefined, database, useArrayBuffer, function (request, exception) {
  60827. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60828. });
  60829. };
  60830. if (directLoad) {
  60831. dataCallback(directLoad);
  60832. return plugin;
  60833. }
  60834. if (rootUrl.indexOf("file:") === -1) {
  60835. if (scene.getEngine().enableOfflineSupport) {
  60836. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60837. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60838. }
  60839. else {
  60840. manifestChecked();
  60841. }
  60842. }
  60843. else {
  60844. var fileOrString = sceneFilename;
  60845. if (fileOrString.name) {
  60846. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60847. }
  60848. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60849. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60850. }
  60851. else {
  60852. onError("Unable to find file named " + sceneFilename);
  60853. }
  60854. }
  60855. return plugin;
  60856. };
  60857. // Public functions
  60858. SceneLoader.GetPluginForExtension = function (extension) {
  60859. return SceneLoader._getPluginForExtension(extension).plugin;
  60860. };
  60861. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60862. return !!SceneLoader._registeredPlugins[extension];
  60863. };
  60864. SceneLoader.RegisterPlugin = function (plugin) {
  60865. if (typeof plugin.extensions === "string") {
  60866. var extension = plugin.extensions;
  60867. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60868. plugin: plugin,
  60869. isBinary: false
  60870. };
  60871. }
  60872. else {
  60873. var extensions = plugin.extensions;
  60874. Object.keys(extensions).forEach(function (extension) {
  60875. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60876. plugin: plugin,
  60877. isBinary: extensions[extension].isBinary
  60878. };
  60879. });
  60880. }
  60881. };
  60882. /**
  60883. * Import meshes into a scene
  60884. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60885. * @param rootUrl a string that defines the root url for scene and resources
  60886. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60887. * @param scene the instance of BABYLON.Scene to append to
  60888. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60889. * @param onProgress a callback with a progress event for each file being loaded
  60890. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60891. * @param pluginExtension the extension used to determine the plugin
  60892. * @returns The loaded plugin
  60893. */
  60894. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60895. if (onSuccess === void 0) { onSuccess = null; }
  60896. if (onProgress === void 0) { onProgress = null; }
  60897. if (onError === void 0) { onError = null; }
  60898. if (pluginExtension === void 0) { pluginExtension = null; }
  60899. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60900. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60901. return null;
  60902. }
  60903. var loadingToken = {};
  60904. scene._addPendingData(loadingToken);
  60905. var disposeHandler = function () {
  60906. scene._removePendingData(loadingToken);
  60907. };
  60908. var errorHandler = function (message, exception) {
  60909. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60910. if (onError) {
  60911. onError(scene, errorMessage, exception);
  60912. }
  60913. else {
  60914. BABYLON.Tools.Error(errorMessage);
  60915. // should the exception be thrown?
  60916. }
  60917. disposeHandler();
  60918. };
  60919. var progressHandler = onProgress ? function (event) {
  60920. try {
  60921. onProgress(event);
  60922. }
  60923. catch (e) {
  60924. errorHandler("Error in onProgress callback", e);
  60925. }
  60926. } : undefined;
  60927. var successHandler = function (meshes, particleSystems, skeletons) {
  60928. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60929. if (onSuccess) {
  60930. try {
  60931. onSuccess(meshes, particleSystems, skeletons);
  60932. }
  60933. catch (e) {
  60934. errorHandler("Error in onSuccess callback", e);
  60935. }
  60936. }
  60937. scene._removePendingData(loadingToken);
  60938. };
  60939. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60940. if (plugin.rewriteRootURL) {
  60941. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60942. }
  60943. if (sceneFilename === "") {
  60944. if (sceneFilename === "") {
  60945. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60946. }
  60947. }
  60948. if (plugin.importMesh) {
  60949. var syncedPlugin = plugin;
  60950. var meshes = new Array();
  60951. var particleSystems = new Array();
  60952. var skeletons = new Array();
  60953. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60954. return;
  60955. }
  60956. scene.loadingPluginName = plugin.name;
  60957. successHandler(meshes, particleSystems, skeletons);
  60958. }
  60959. else {
  60960. var asyncedPlugin = plugin;
  60961. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60962. scene.loadingPluginName = plugin.name;
  60963. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60964. }).catch(function (error) {
  60965. errorHandler(error.message, error);
  60966. });
  60967. }
  60968. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60969. };
  60970. /**
  60971. * Import meshes into a scene
  60972. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60973. * @param rootUrl a string that defines the root url for scene and resources
  60974. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60975. * @param scene the instance of BABYLON.Scene to append to
  60976. * @param onProgress a callback with a progress event for each file being loaded
  60977. * @param pluginExtension the extension used to determine the plugin
  60978. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60979. */
  60980. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60981. if (onProgress === void 0) { onProgress = null; }
  60982. if (pluginExtension === void 0) { pluginExtension = null; }
  60983. return new Promise(function (resolve, reject) {
  60984. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60985. resolve({
  60986. meshes: meshes,
  60987. particleSystems: particleSystems,
  60988. skeletons: skeletons
  60989. });
  60990. }, onProgress, function (scene, message, exception) {
  60991. reject(exception || new Error(message));
  60992. });
  60993. });
  60994. };
  60995. /**
  60996. * Load a scene
  60997. * @param rootUrl a string that defines the root url for scene and resources
  60998. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60999. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61000. * @param onSuccess a callback with the scene when import succeeds
  61001. * @param onProgress a callback with a progress event for each file being loaded
  61002. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61003. * @param pluginExtension the extension used to determine the plugin
  61004. * @returns The loaded plugin
  61005. */
  61006. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61007. if (onSuccess === void 0) { onSuccess = null; }
  61008. if (onProgress === void 0) { onProgress = null; }
  61009. if (onError === void 0) { onError = null; }
  61010. if (pluginExtension === void 0) { pluginExtension = null; }
  61011. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61012. };
  61013. /**
  61014. * Load a scene
  61015. * @param rootUrl a string that defines the root url for scene and resources
  61016. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61017. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61018. * @param onProgress a callback with a progress event for each file being loaded
  61019. * @param pluginExtension the extension used to determine the plugin
  61020. * @returns The loaded scene
  61021. */
  61022. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61023. if (onProgress === void 0) { onProgress = null; }
  61024. if (pluginExtension === void 0) { pluginExtension = null; }
  61025. return new Promise(function (resolve, reject) {
  61026. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61027. resolve(scene);
  61028. }, onProgress, function (scene, message, exception) {
  61029. reject(exception || new Error(message));
  61030. }, pluginExtension);
  61031. });
  61032. };
  61033. /**
  61034. * Append a scene
  61035. * @param rootUrl a string that defines the root url for scene and resources
  61036. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61037. * @param scene is the instance of BABYLON.Scene to append to
  61038. * @param onSuccess a callback with the scene when import succeeds
  61039. * @param onProgress a callback with a progress event for each file being loaded
  61040. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61041. * @param pluginExtension the extension used to determine the plugin
  61042. * @returns The loaded plugin
  61043. */
  61044. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61045. if (onSuccess === void 0) { onSuccess = null; }
  61046. if (onProgress === void 0) { onProgress = null; }
  61047. if (onError === void 0) { onError = null; }
  61048. if (pluginExtension === void 0) { pluginExtension = null; }
  61049. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61050. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61051. return null;
  61052. }
  61053. if (SceneLoader.ShowLoadingScreen) {
  61054. scene.getEngine().displayLoadingUI();
  61055. }
  61056. var loadingToken = {};
  61057. scene._addPendingData(loadingToken);
  61058. var disposeHandler = function () {
  61059. scene._removePendingData(loadingToken);
  61060. scene.getEngine().hideLoadingUI();
  61061. };
  61062. var errorHandler = function (message, exception) {
  61063. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61064. if (onError) {
  61065. onError(scene, errorMessage, exception);
  61066. }
  61067. else {
  61068. BABYLON.Tools.Error(errorMessage);
  61069. // should the exception be thrown?
  61070. }
  61071. disposeHandler();
  61072. };
  61073. var progressHandler = onProgress ? function (event) {
  61074. try {
  61075. onProgress(event);
  61076. }
  61077. catch (e) {
  61078. errorHandler("Error in onProgress callback", e);
  61079. }
  61080. } : undefined;
  61081. var successHandler = function () {
  61082. if (onSuccess) {
  61083. try {
  61084. onSuccess(scene);
  61085. }
  61086. catch (e) {
  61087. errorHandler("Error in onSuccess callback", e);
  61088. }
  61089. }
  61090. scene._removePendingData(loadingToken);
  61091. };
  61092. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61093. if (sceneFilename === "") {
  61094. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61095. }
  61096. if (plugin.load) {
  61097. var syncedPlugin = plugin;
  61098. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61099. return;
  61100. }
  61101. scene.loadingPluginName = plugin.name;
  61102. successHandler();
  61103. }
  61104. else {
  61105. var asyncedPlugin = plugin;
  61106. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61107. scene.loadingPluginName = plugin.name;
  61108. successHandler();
  61109. }).catch(function (error) {
  61110. errorHandler(error.message, error);
  61111. });
  61112. }
  61113. if (SceneLoader.ShowLoadingScreen) {
  61114. scene.executeWhenReady(function () {
  61115. scene.getEngine().hideLoadingUI();
  61116. });
  61117. }
  61118. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61119. };
  61120. /**
  61121. * Append a scene
  61122. * @param rootUrl a string that defines the root url for scene and resources
  61123. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61124. * @param scene is the instance of BABYLON.Scene to append to
  61125. * @param onProgress a callback with a progress event for each file being loaded
  61126. * @param pluginExtension the extension used to determine the plugin
  61127. * @returns The given scene
  61128. */
  61129. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61130. if (onProgress === void 0) { onProgress = null; }
  61131. if (pluginExtension === void 0) { pluginExtension = null; }
  61132. return new Promise(function (resolve, reject) {
  61133. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61134. resolve(scene);
  61135. }, onProgress, function (scene, message, exception) {
  61136. reject(exception || new Error(message));
  61137. }, pluginExtension);
  61138. });
  61139. };
  61140. /**
  61141. * Load a scene into an asset container
  61142. * @param rootUrl a string that defines the root url for scene and resources
  61143. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61144. * @param scene is the instance of BABYLON.Scene to append to
  61145. * @param onSuccess a callback with the scene when import succeeds
  61146. * @param onProgress a callback with a progress event for each file being loaded
  61147. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61148. * @param pluginExtension the extension used to determine the plugin
  61149. * @returns The loaded plugin
  61150. */
  61151. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61152. if (onSuccess === void 0) { onSuccess = null; }
  61153. if (onProgress === void 0) { onProgress = null; }
  61154. if (onError === void 0) { onError = null; }
  61155. if (pluginExtension === void 0) { pluginExtension = null; }
  61156. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61157. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61158. return null;
  61159. }
  61160. var loadingToken = {};
  61161. scene._addPendingData(loadingToken);
  61162. var disposeHandler = function () {
  61163. scene._removePendingData(loadingToken);
  61164. };
  61165. var errorHandler = function (message, exception) {
  61166. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61167. if (onError) {
  61168. onError(scene, errorMessage, exception);
  61169. }
  61170. else {
  61171. BABYLON.Tools.Error(errorMessage);
  61172. // should the exception be thrown?
  61173. }
  61174. disposeHandler();
  61175. };
  61176. var progressHandler = onProgress ? function (event) {
  61177. try {
  61178. onProgress(event);
  61179. }
  61180. catch (e) {
  61181. errorHandler("Error in onProgress callback", e);
  61182. }
  61183. } : undefined;
  61184. var successHandler = function (assets) {
  61185. if (onSuccess) {
  61186. try {
  61187. onSuccess(assets);
  61188. }
  61189. catch (e) {
  61190. errorHandler("Error in onSuccess callback", e);
  61191. }
  61192. }
  61193. scene._removePendingData(loadingToken);
  61194. };
  61195. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61196. if (plugin.loadAssetContainer) {
  61197. var syncedPlugin = plugin;
  61198. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61199. if (!assetContainer) {
  61200. return;
  61201. }
  61202. scene.loadingPluginName = plugin.name;
  61203. successHandler(assetContainer);
  61204. }
  61205. else if (plugin.loadAssetContainerAsync) {
  61206. var asyncedPlugin = plugin;
  61207. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61208. scene.loadingPluginName = plugin.name;
  61209. successHandler(assetContainer);
  61210. }).catch(function (error) {
  61211. errorHandler(error.message, error);
  61212. });
  61213. }
  61214. else {
  61215. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61216. }
  61217. if (SceneLoader.ShowLoadingScreen) {
  61218. scene.executeWhenReady(function () {
  61219. scene.getEngine().hideLoadingUI();
  61220. });
  61221. }
  61222. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61223. };
  61224. /**
  61225. * Load a scene into an asset container
  61226. * @param rootUrl a string that defines the root url for scene and resources
  61227. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61228. * @param scene is the instance of BABYLON.Scene to append to
  61229. * @param onProgress a callback with a progress event for each file being loaded
  61230. * @param pluginExtension the extension used to determine the plugin
  61231. * @returns The loaded asset container
  61232. */
  61233. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61234. if (onProgress === void 0) { onProgress = null; }
  61235. if (pluginExtension === void 0) { pluginExtension = null; }
  61236. return new Promise(function (resolve, reject) {
  61237. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61238. resolve(assetContainer);
  61239. }, onProgress, function (scene, message, exception) {
  61240. reject(exception || new Error(message));
  61241. }, pluginExtension);
  61242. });
  61243. };
  61244. // Flags
  61245. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61246. SceneLoader._ShowLoadingScreen = true;
  61247. SceneLoader._CleanBoneMatrixWeights = false;
  61248. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61249. // Members
  61250. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61251. SceneLoader._registeredPlugins = {};
  61252. return SceneLoader;
  61253. }());
  61254. BABYLON.SceneLoader = SceneLoader;
  61255. ;
  61256. })(BABYLON || (BABYLON = {}));
  61257. //# sourceMappingURL=babylon.sceneLoader.js.map
  61258. var BABYLON;
  61259. (function (BABYLON) {
  61260. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61261. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61262. var parsedMaterial = parsedData.materials[index];
  61263. if (parsedMaterial.id === id) {
  61264. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61265. }
  61266. }
  61267. return null;
  61268. };
  61269. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61270. for (var i in names) {
  61271. if (mesh.name === names[i]) {
  61272. hierarchyIds.push(mesh.id);
  61273. return true;
  61274. }
  61275. }
  61276. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61277. hierarchyIds.push(mesh.id);
  61278. return true;
  61279. }
  61280. return false;
  61281. };
  61282. var logOperation = function (operation, producer) {
  61283. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61284. };
  61285. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61286. if (addToScene === void 0) { addToScene = false; }
  61287. var container = new BABYLON.AssetContainer(scene);
  61288. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61289. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61290. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61291. // and avoid problems with multiple concurrent .babylon loads.
  61292. var log = "importScene has failed JSON parse";
  61293. try {
  61294. var parsedData = JSON.parse(data);
  61295. log = "";
  61296. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61297. var index;
  61298. var cache;
  61299. // Lights
  61300. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61301. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61302. var parsedLight = parsedData.lights[index];
  61303. var light = BABYLON.Light.Parse(parsedLight, scene);
  61304. if (light) {
  61305. container.lights.push(light);
  61306. log += (index === 0 ? "\n\tLights:" : "");
  61307. log += "\n\t\t" + light.toString(fullDetails);
  61308. }
  61309. }
  61310. }
  61311. // Animations
  61312. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61313. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61314. var parsedAnimation = parsedData.animations[index];
  61315. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61316. scene.animations.push(animation);
  61317. container.animations.push(animation);
  61318. log += (index === 0 ? "\n\tAnimations:" : "");
  61319. log += "\n\t\t" + animation.toString(fullDetails);
  61320. }
  61321. }
  61322. // Materials
  61323. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61324. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61325. var parsedMaterial = parsedData.materials[index];
  61326. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61327. container.materials.push(mat);
  61328. log += (index === 0 ? "\n\tMaterials:" : "");
  61329. log += "\n\t\t" + mat.toString(fullDetails);
  61330. }
  61331. }
  61332. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61333. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61334. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61335. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61336. container.multiMaterials.push(mmat);
  61337. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61338. log += "\n\t\t" + mmat.toString(fullDetails);
  61339. }
  61340. }
  61341. // Morph targets
  61342. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61343. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61344. var managerData = _a[_i];
  61345. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61346. }
  61347. }
  61348. // Skeletons
  61349. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61350. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61351. var parsedSkeleton = parsedData.skeletons[index];
  61352. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61353. container.skeletons.push(skeleton);
  61354. log += (index === 0 ? "\n\tSkeletons:" : "");
  61355. log += "\n\t\t" + skeleton.toString(fullDetails);
  61356. }
  61357. }
  61358. // Geometries
  61359. var geometries = parsedData.geometries;
  61360. if (geometries !== undefined && geometries !== null) {
  61361. var addedGeometry = new Array();
  61362. // Boxes
  61363. var boxes = geometries.boxes;
  61364. if (boxes !== undefined && boxes !== null) {
  61365. for (index = 0, cache = boxes.length; index < cache; index++) {
  61366. var parsedBox = boxes[index];
  61367. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61368. }
  61369. }
  61370. // Spheres
  61371. var spheres = geometries.spheres;
  61372. if (spheres !== undefined && spheres !== null) {
  61373. for (index = 0, cache = spheres.length; index < cache; index++) {
  61374. var parsedSphere = spheres[index];
  61375. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61376. }
  61377. }
  61378. // Cylinders
  61379. var cylinders = geometries.cylinders;
  61380. if (cylinders !== undefined && cylinders !== null) {
  61381. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61382. var parsedCylinder = cylinders[index];
  61383. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61384. }
  61385. }
  61386. // Toruses
  61387. var toruses = geometries.toruses;
  61388. if (toruses !== undefined && toruses !== null) {
  61389. for (index = 0, cache = toruses.length; index < cache; index++) {
  61390. var parsedTorus = toruses[index];
  61391. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61392. }
  61393. }
  61394. // Grounds
  61395. var grounds = geometries.grounds;
  61396. if (grounds !== undefined && grounds !== null) {
  61397. for (index = 0, cache = grounds.length; index < cache; index++) {
  61398. var parsedGround = grounds[index];
  61399. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61400. }
  61401. }
  61402. // Planes
  61403. var planes = geometries.planes;
  61404. if (planes !== undefined && planes !== null) {
  61405. for (index = 0, cache = planes.length; index < cache; index++) {
  61406. var parsedPlane = planes[index];
  61407. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61408. }
  61409. }
  61410. // TorusKnots
  61411. var torusKnots = geometries.torusKnots;
  61412. if (torusKnots !== undefined && torusKnots !== null) {
  61413. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61414. var parsedTorusKnot = torusKnots[index];
  61415. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61416. }
  61417. }
  61418. // VertexData
  61419. var vertexData = geometries.vertexData;
  61420. if (vertexData !== undefined && vertexData !== null) {
  61421. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61422. var parsedVertexData = vertexData[index];
  61423. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61424. }
  61425. }
  61426. addedGeometry.forEach(function (g) {
  61427. if (g) {
  61428. container.geometries.push(g);
  61429. }
  61430. });
  61431. }
  61432. // Transform nodes
  61433. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61434. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61435. var parsedTransformNode = parsedData.transformNodes[index];
  61436. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61437. container.transformNodes.push(node);
  61438. }
  61439. }
  61440. // Meshes
  61441. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61442. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61443. var parsedMesh = parsedData.meshes[index];
  61444. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61445. container.meshes.push(mesh);
  61446. log += (index === 0 ? "\n\tMeshes:" : "");
  61447. log += "\n\t\t" + mesh.toString(fullDetails);
  61448. }
  61449. }
  61450. // Cameras
  61451. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61452. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61453. var parsedCamera = parsedData.cameras[index];
  61454. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61455. container.cameras.push(camera);
  61456. log += (index === 0 ? "\n\tCameras:" : "");
  61457. log += "\n\t\t" + camera.toString(fullDetails);
  61458. }
  61459. }
  61460. // Browsing all the graph to connect the dots
  61461. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61462. var camera = scene.cameras[index];
  61463. if (camera._waitingParentId) {
  61464. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61465. camera._waitingParentId = null;
  61466. }
  61467. }
  61468. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61469. var light_1 = scene.lights[index];
  61470. if (light_1 && light_1._waitingParentId) {
  61471. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61472. light_1._waitingParentId = null;
  61473. }
  61474. }
  61475. // Sounds
  61476. // TODO: add sound
  61477. var loadedSounds = [];
  61478. var loadedSound;
  61479. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61480. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61481. var parsedSound = parsedData.sounds[index];
  61482. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61483. if (!parsedSound.url)
  61484. parsedSound.url = parsedSound.name;
  61485. if (!loadedSounds[parsedSound.url]) {
  61486. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61487. loadedSounds[parsedSound.url] = loadedSound;
  61488. container.sounds.push(loadedSound);
  61489. }
  61490. else {
  61491. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61492. }
  61493. }
  61494. else {
  61495. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61496. }
  61497. }
  61498. }
  61499. loadedSounds = [];
  61500. // Connect parents & children and parse actions
  61501. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61502. var transformNode = scene.transformNodes[index];
  61503. if (transformNode._waitingParentId) {
  61504. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61505. transformNode._waitingParentId = null;
  61506. }
  61507. }
  61508. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61509. var mesh = scene.meshes[index];
  61510. if (mesh._waitingParentId) {
  61511. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61512. mesh._waitingParentId = null;
  61513. }
  61514. if (mesh._waitingActions) {
  61515. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61516. mesh._waitingActions = null;
  61517. }
  61518. }
  61519. // freeze world matrix application
  61520. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61521. var currentMesh = scene.meshes[index];
  61522. if (currentMesh._waitingFreezeWorldMatrix) {
  61523. currentMesh.freezeWorldMatrix();
  61524. currentMesh._waitingFreezeWorldMatrix = null;
  61525. }
  61526. else {
  61527. currentMesh.computeWorldMatrix(true);
  61528. }
  61529. }
  61530. // Particles Systems
  61531. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61532. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61533. var parsedParticleSystem = parsedData.particleSystems[index];
  61534. if (parsedParticleSystem.activeParticleCount) {
  61535. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61536. container.particleSystems.push(ps);
  61537. }
  61538. else {
  61539. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61540. container.particleSystems.push(ps);
  61541. }
  61542. }
  61543. }
  61544. // Lens flares
  61545. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61546. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61547. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61548. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61549. container.lensFlareSystems.push(lf);
  61550. }
  61551. }
  61552. // Shadows
  61553. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61554. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61555. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61556. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61557. container.shadowGenerators.push(sg);
  61558. }
  61559. }
  61560. // Lights exclusions / inclusions
  61561. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61562. var light_2 = scene.lights[index];
  61563. // Excluded check
  61564. if (light_2._excludedMeshesIds.length > 0) {
  61565. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61566. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61567. if (excludedMesh) {
  61568. light_2.excludedMeshes.push(excludedMesh);
  61569. }
  61570. }
  61571. light_2._excludedMeshesIds = [];
  61572. }
  61573. // Included check
  61574. if (light_2._includedOnlyMeshesIds.length > 0) {
  61575. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61576. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61577. if (includedOnlyMesh) {
  61578. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61579. }
  61580. }
  61581. light_2._includedOnlyMeshesIds = [];
  61582. }
  61583. }
  61584. // Actions (scene)
  61585. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61586. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61587. }
  61588. if (!addToScene) {
  61589. container.removeAllFromScene();
  61590. }
  61591. }
  61592. catch (err) {
  61593. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61594. if (onError) {
  61595. onError(msg, err);
  61596. }
  61597. else {
  61598. BABYLON.Tools.Log(msg);
  61599. throw err;
  61600. }
  61601. }
  61602. finally {
  61603. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61604. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61605. }
  61606. }
  61607. return container;
  61608. };
  61609. BABYLON.SceneLoader.RegisterPlugin({
  61610. name: "babylon.js",
  61611. extensions: ".babylon",
  61612. canDirectLoad: function (data) {
  61613. if (data.indexOf("babylon") !== -1) {
  61614. return true;
  61615. }
  61616. return false;
  61617. },
  61618. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61619. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61620. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61621. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61622. // and avoid problems with multiple concurrent .babylon loads.
  61623. var log = "importMesh has failed JSON parse";
  61624. try {
  61625. var parsedData = JSON.parse(data);
  61626. log = "";
  61627. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61628. if (!meshesNames) {
  61629. meshesNames = null;
  61630. }
  61631. else if (!Array.isArray(meshesNames)) {
  61632. meshesNames = [meshesNames];
  61633. }
  61634. var hierarchyIds = new Array();
  61635. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61636. var loadedSkeletonsIds = [];
  61637. var loadedMaterialsIds = [];
  61638. var index;
  61639. var cache;
  61640. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61641. var parsedMesh = parsedData.meshes[index];
  61642. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61643. if (meshesNames !== null) {
  61644. // Remove found mesh name from list.
  61645. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61646. }
  61647. //Geometry?
  61648. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61649. //does the file contain geometries?
  61650. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61651. //find the correct geometry and add it to the scene
  61652. var found = false;
  61653. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61654. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61655. return;
  61656. }
  61657. else {
  61658. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61659. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61660. switch (geometryType) {
  61661. case "boxes":
  61662. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61663. break;
  61664. case "spheres":
  61665. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61666. break;
  61667. case "cylinders":
  61668. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61669. break;
  61670. case "toruses":
  61671. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61672. break;
  61673. case "grounds":
  61674. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61675. break;
  61676. case "planes":
  61677. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61678. break;
  61679. case "torusKnots":
  61680. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61681. break;
  61682. case "vertexData":
  61683. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61684. break;
  61685. }
  61686. found = true;
  61687. }
  61688. });
  61689. }
  61690. });
  61691. if (found === false) {
  61692. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61693. }
  61694. }
  61695. }
  61696. // Material ?
  61697. if (parsedMesh.materialId) {
  61698. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61699. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61700. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61701. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61702. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61703. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61704. var subMatId = parsedMultiMaterial.materials[matIndex];
  61705. loadedMaterialsIds.push(subMatId);
  61706. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61707. if (mat) {
  61708. log += "\n\tMaterial " + mat.toString(fullDetails);
  61709. }
  61710. }
  61711. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61712. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61713. if (mmat) {
  61714. materialFound = true;
  61715. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61716. }
  61717. break;
  61718. }
  61719. }
  61720. }
  61721. if (materialFound === false) {
  61722. loadedMaterialsIds.push(parsedMesh.materialId);
  61723. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61724. if (!mat) {
  61725. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61726. }
  61727. else {
  61728. log += "\n\tMaterial " + mat.toString(fullDetails);
  61729. }
  61730. }
  61731. }
  61732. // Skeleton ?
  61733. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61734. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61735. if (skeletonAlreadyLoaded === false) {
  61736. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61737. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61738. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61739. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61740. skeletons.push(skeleton);
  61741. loadedSkeletonsIds.push(parsedSkeleton.id);
  61742. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61743. }
  61744. }
  61745. }
  61746. }
  61747. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61748. meshes.push(mesh);
  61749. log += "\n\tMesh " + mesh.toString(fullDetails);
  61750. }
  61751. }
  61752. // Connecting parents
  61753. var currentMesh;
  61754. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61755. currentMesh = scene.meshes[index];
  61756. if (currentMesh._waitingParentId) {
  61757. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61758. currentMesh._waitingParentId = null;
  61759. }
  61760. }
  61761. // freeze and compute world matrix application
  61762. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61763. currentMesh = scene.meshes[index];
  61764. if (currentMesh._waitingFreezeWorldMatrix) {
  61765. currentMesh.freezeWorldMatrix();
  61766. currentMesh._waitingFreezeWorldMatrix = null;
  61767. }
  61768. else {
  61769. currentMesh.computeWorldMatrix(true);
  61770. }
  61771. }
  61772. }
  61773. // Particles
  61774. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61775. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61776. var parsedParticleSystem = parsedData.particleSystems[index];
  61777. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61778. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61779. }
  61780. }
  61781. }
  61782. return true;
  61783. }
  61784. catch (err) {
  61785. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61786. if (onError) {
  61787. onError(msg, err);
  61788. }
  61789. else {
  61790. BABYLON.Tools.Log(msg);
  61791. throw err;
  61792. }
  61793. }
  61794. finally {
  61795. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61796. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61797. }
  61798. }
  61799. return false;
  61800. },
  61801. load: function (scene, data, rootUrl, onError) {
  61802. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61803. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61804. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61805. // and avoid problems with multiple concurrent .babylon loads.
  61806. var log = "importScene has failed JSON parse";
  61807. try {
  61808. var parsedData = JSON.parse(data);
  61809. log = "";
  61810. // Scene
  61811. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61812. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61813. }
  61814. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61815. scene.autoClear = parsedData.autoClear;
  61816. }
  61817. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61818. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61819. }
  61820. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61821. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61822. }
  61823. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61824. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61825. }
  61826. // Fog
  61827. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61828. scene.fogMode = parsedData.fogMode;
  61829. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61830. scene.fogStart = parsedData.fogStart;
  61831. scene.fogEnd = parsedData.fogEnd;
  61832. scene.fogDensity = parsedData.fogDensity;
  61833. log += "\tFog mode for scene: ";
  61834. switch (scene.fogMode) {
  61835. // getters not compiling, so using hardcoded
  61836. case 1:
  61837. log += "exp\n";
  61838. break;
  61839. case 2:
  61840. log += "exp2\n";
  61841. break;
  61842. case 3:
  61843. log += "linear\n";
  61844. break;
  61845. }
  61846. }
  61847. //Physics
  61848. if (parsedData.physicsEnabled) {
  61849. var physicsPlugin;
  61850. if (parsedData.physicsEngine === "cannon") {
  61851. physicsPlugin = new BABYLON.CannonJSPlugin();
  61852. }
  61853. else if (parsedData.physicsEngine === "oimo") {
  61854. physicsPlugin = new BABYLON.OimoJSPlugin();
  61855. }
  61856. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61857. //else - default engine, which is currently oimo
  61858. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61859. scene.enablePhysics(physicsGravity, physicsPlugin);
  61860. }
  61861. // Metadata
  61862. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61863. scene.metadata = parsedData.metadata;
  61864. }
  61865. //collisions, if defined. otherwise, default is true
  61866. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61867. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61868. }
  61869. scene.workerCollisions = !!parsedData.workerCollisions;
  61870. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61871. if (!container) {
  61872. return false;
  61873. }
  61874. if (parsedData.autoAnimate) {
  61875. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61876. }
  61877. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61878. scene.setActiveCameraByID(parsedData.activeCameraID);
  61879. }
  61880. // Environment texture
  61881. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61882. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61883. if (parsedData.createDefaultSkybox === true) {
  61884. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61885. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61886. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61887. }
  61888. }
  61889. // Finish
  61890. return true;
  61891. }
  61892. catch (err) {
  61893. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61894. if (onError) {
  61895. onError(msg, err);
  61896. }
  61897. else {
  61898. BABYLON.Tools.Log(msg);
  61899. throw err;
  61900. }
  61901. }
  61902. finally {
  61903. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61904. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61905. }
  61906. }
  61907. return false;
  61908. },
  61909. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61910. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61911. return container;
  61912. }
  61913. });
  61914. })(BABYLON || (BABYLON = {}));
  61915. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61916. var BABYLON;
  61917. (function (BABYLON) {
  61918. var FilesInput = /** @class */ (function () {
  61919. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61920. this.onProcessFileCallback = function () { return true; };
  61921. this._engine = engine;
  61922. this._currentScene = scene;
  61923. this._sceneLoadedCallback = sceneLoadedCallback;
  61924. this._progressCallback = progressCallback;
  61925. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61926. this._textureLoadingCallback = textureLoadingCallback;
  61927. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61928. this._onReloadCallback = onReloadCallback;
  61929. this._errorCallback = errorCallback;
  61930. }
  61931. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61932. var _this = this;
  61933. if (elementToMonitor) {
  61934. this._elementToMonitor = elementToMonitor;
  61935. this._dragEnterHandler = function (e) { _this.drag(e); };
  61936. this._dragOverHandler = function (e) { _this.drag(e); };
  61937. this._dropHandler = function (e) { _this.drop(e); };
  61938. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61939. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61940. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61941. }
  61942. };
  61943. FilesInput.prototype.dispose = function () {
  61944. if (!this._elementToMonitor) {
  61945. return;
  61946. }
  61947. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61948. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61949. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61950. };
  61951. FilesInput.prototype.renderFunction = function () {
  61952. if (this._additionalRenderLoopLogicCallback) {
  61953. this._additionalRenderLoopLogicCallback();
  61954. }
  61955. if (this._currentScene) {
  61956. if (this._textureLoadingCallback) {
  61957. var remaining = this._currentScene.getWaitingItemsCount();
  61958. if (remaining > 0) {
  61959. this._textureLoadingCallback(remaining);
  61960. }
  61961. }
  61962. this._currentScene.render();
  61963. }
  61964. };
  61965. FilesInput.prototype.drag = function (e) {
  61966. e.stopPropagation();
  61967. e.preventDefault();
  61968. };
  61969. FilesInput.prototype.drop = function (eventDrop) {
  61970. eventDrop.stopPropagation();
  61971. eventDrop.preventDefault();
  61972. this.loadFiles(eventDrop);
  61973. };
  61974. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61975. var _this = this;
  61976. var reader = folder.createReader();
  61977. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61978. reader.readEntries(function (entries) {
  61979. remaining.count += entries.length;
  61980. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61981. var entry = entries_1[_i];
  61982. if (entry.isFile) {
  61983. entry.file(function (file) {
  61984. file.correctName = relativePath + file.name;
  61985. files.push(file);
  61986. if (--remaining.count === 0) {
  61987. callback();
  61988. }
  61989. });
  61990. }
  61991. else if (entry.isDirectory) {
  61992. _this._traverseFolder(entry, files, remaining, callback);
  61993. }
  61994. }
  61995. if (--remaining.count) {
  61996. callback();
  61997. }
  61998. });
  61999. };
  62000. FilesInput.prototype._processFiles = function (files) {
  62001. for (var i = 0; i < files.length; i++) {
  62002. var name = files[i].correctName.toLowerCase();
  62003. var extension = name.split('.').pop();
  62004. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62005. continue;
  62006. }
  62007. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62008. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62009. this._sceneFileToLoad = files[i];
  62010. }
  62011. else {
  62012. FilesInput.FilesToLoad[name] = files[i];
  62013. }
  62014. }
  62015. };
  62016. FilesInput.prototype.loadFiles = function (event) {
  62017. var _this = this;
  62018. if (this._startingProcessingFilesCallback)
  62019. this._startingProcessingFilesCallback();
  62020. // Handling data transfer via drag'n'drop
  62021. if (event && event.dataTransfer && event.dataTransfer.files) {
  62022. this._filesToLoad = event.dataTransfer.files;
  62023. }
  62024. // Handling files from input files
  62025. if (event && event.target && event.target.files) {
  62026. this._filesToLoad = event.target.files;
  62027. }
  62028. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62029. var files_1 = new Array();
  62030. var folders = [];
  62031. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62032. for (var i = 0; i < this._filesToLoad.length; i++) {
  62033. var fileToLoad = this._filesToLoad[i];
  62034. var name_1 = fileToLoad.name.toLowerCase();
  62035. var entry = void 0;
  62036. fileToLoad.correctName = name_1;
  62037. if (items) {
  62038. var item = items[i];
  62039. if (item.getAsEntry) {
  62040. entry = item.getAsEntry();
  62041. }
  62042. else if (item.webkitGetAsEntry) {
  62043. entry = item.webkitGetAsEntry();
  62044. }
  62045. }
  62046. if (!entry) {
  62047. files_1.push(fileToLoad);
  62048. }
  62049. else {
  62050. if (entry.isDirectory) {
  62051. folders.push(entry);
  62052. }
  62053. else {
  62054. files_1.push(fileToLoad);
  62055. }
  62056. }
  62057. }
  62058. if (folders.length === 0) {
  62059. this._processFiles(files_1);
  62060. this._processReload();
  62061. }
  62062. else {
  62063. var remaining = { count: folders.length };
  62064. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62065. var folder = folders_1[_i];
  62066. this._traverseFolder(folder, files_1, remaining, function () {
  62067. _this._processFiles(files_1);
  62068. if (remaining.count === 0) {
  62069. _this._processReload();
  62070. }
  62071. });
  62072. }
  62073. }
  62074. }
  62075. };
  62076. FilesInput.prototype._processReload = function () {
  62077. if (this._onReloadCallback) {
  62078. this._onReloadCallback(this._sceneFileToLoad);
  62079. }
  62080. else {
  62081. this.reload();
  62082. }
  62083. };
  62084. FilesInput.prototype.reload = function () {
  62085. var _this = this;
  62086. // If a scene file has been provided
  62087. if (this._sceneFileToLoad) {
  62088. if (this._currentScene) {
  62089. if (BABYLON.Tools.errorsCount > 0) {
  62090. BABYLON.Tools.ClearLogCache();
  62091. }
  62092. this._engine.stopRenderLoop();
  62093. this._currentScene.dispose();
  62094. }
  62095. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62096. if (_this._progressCallback) {
  62097. _this._progressCallback(progress);
  62098. }
  62099. }).then(function (scene) {
  62100. _this._currentScene = scene;
  62101. if (_this._sceneLoadedCallback) {
  62102. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62103. }
  62104. // Wait for textures and shaders to be ready
  62105. _this._currentScene.executeWhenReady(function () {
  62106. _this._engine.runRenderLoop(function () {
  62107. _this.renderFunction();
  62108. });
  62109. });
  62110. }).catch(function (error) {
  62111. if (_this._errorCallback) {
  62112. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62113. }
  62114. });
  62115. }
  62116. else {
  62117. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62118. }
  62119. };
  62120. FilesInput.FilesToLoad = {};
  62121. return FilesInput;
  62122. }());
  62123. BABYLON.FilesInput = FilesInput;
  62124. })(BABYLON || (BABYLON = {}));
  62125. //# sourceMappingURL=babylon.filesInput.js.map
  62126. var BABYLON;
  62127. (function (BABYLON) {
  62128. /**
  62129. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62130. * The underlying implementation relies on an associative array to ensure the best performances.
  62131. * The value can be anything including 'null' but except 'undefined'
  62132. */
  62133. var StringDictionary = /** @class */ (function () {
  62134. function StringDictionary() {
  62135. this._count = 0;
  62136. this._data = {};
  62137. }
  62138. /**
  62139. * This will clear this dictionary and copy the content from the 'source' one.
  62140. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62141. * @param source the dictionary to take the content from and copy to this dictionary
  62142. */
  62143. StringDictionary.prototype.copyFrom = function (source) {
  62144. var _this = this;
  62145. this.clear();
  62146. source.forEach(function (t, v) { return _this.add(t, v); });
  62147. };
  62148. /**
  62149. * Get a value based from its key
  62150. * @param key the given key to get the matching value from
  62151. * @return the value if found, otherwise undefined is returned
  62152. */
  62153. StringDictionary.prototype.get = function (key) {
  62154. var val = this._data[key];
  62155. if (val !== undefined) {
  62156. return val;
  62157. }
  62158. return undefined;
  62159. };
  62160. /**
  62161. * Get a value from its key or add it if it doesn't exist.
  62162. * This method will ensure you that a given key/data will be present in the dictionary.
  62163. * @param key the given key to get the matching value from
  62164. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62165. * The factory will only be invoked if there's no data for the given key.
  62166. * @return the value corresponding to the key.
  62167. */
  62168. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62169. var val = this.get(key);
  62170. if (val !== undefined) {
  62171. return val;
  62172. }
  62173. val = factory(key);
  62174. if (val) {
  62175. this.add(key, val);
  62176. }
  62177. return val;
  62178. };
  62179. /**
  62180. * Get a value from its key if present in the dictionary otherwise add it
  62181. * @param key the key to get the value from
  62182. * @param val if there's no such key/value pair in the dictionary add it with this value
  62183. * @return the value corresponding to the key
  62184. */
  62185. StringDictionary.prototype.getOrAdd = function (key, val) {
  62186. var curVal = this.get(key);
  62187. if (curVal !== undefined) {
  62188. return curVal;
  62189. }
  62190. this.add(key, val);
  62191. return val;
  62192. };
  62193. /**
  62194. * Check if there's a given key in the dictionary
  62195. * @param key the key to check for
  62196. * @return true if the key is present, false otherwise
  62197. */
  62198. StringDictionary.prototype.contains = function (key) {
  62199. return this._data[key] !== undefined;
  62200. };
  62201. /**
  62202. * Add a new key and its corresponding value
  62203. * @param key the key to add
  62204. * @param value the value corresponding to the key
  62205. * @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
  62206. */
  62207. StringDictionary.prototype.add = function (key, value) {
  62208. if (this._data[key] !== undefined) {
  62209. return false;
  62210. }
  62211. this._data[key] = value;
  62212. ++this._count;
  62213. return true;
  62214. };
  62215. StringDictionary.prototype.set = function (key, value) {
  62216. if (this._data[key] === undefined) {
  62217. return false;
  62218. }
  62219. this._data[key] = value;
  62220. return true;
  62221. };
  62222. /**
  62223. * Get the element of the given key and remove it from the dictionary
  62224. * @param key
  62225. */
  62226. StringDictionary.prototype.getAndRemove = function (key) {
  62227. var val = this.get(key);
  62228. if (val !== undefined) {
  62229. delete this._data[key];
  62230. --this._count;
  62231. return val;
  62232. }
  62233. return null;
  62234. };
  62235. /**
  62236. * Remove a key/value from the dictionary.
  62237. * @param key the key to remove
  62238. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62239. */
  62240. StringDictionary.prototype.remove = function (key) {
  62241. if (this.contains(key)) {
  62242. delete this._data[key];
  62243. --this._count;
  62244. return true;
  62245. }
  62246. return false;
  62247. };
  62248. /**
  62249. * Clear the whole content of the dictionary
  62250. */
  62251. StringDictionary.prototype.clear = function () {
  62252. this._data = {};
  62253. this._count = 0;
  62254. };
  62255. Object.defineProperty(StringDictionary.prototype, "count", {
  62256. get: function () {
  62257. return this._count;
  62258. },
  62259. enumerable: true,
  62260. configurable: true
  62261. });
  62262. /**
  62263. * Execute a callback on each key/val of the dictionary.
  62264. * Note that you can remove any element in this dictionary in the callback implementation
  62265. * @param callback the callback to execute on a given key/value pair
  62266. */
  62267. StringDictionary.prototype.forEach = function (callback) {
  62268. for (var cur in this._data) {
  62269. var val = this._data[cur];
  62270. callback(cur, val);
  62271. }
  62272. };
  62273. /**
  62274. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62275. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62276. * Note that you can remove any element in this dictionary in the callback implementation
  62277. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62278. */
  62279. StringDictionary.prototype.first = function (callback) {
  62280. for (var cur in this._data) {
  62281. var val = this._data[cur];
  62282. var res = callback(cur, val);
  62283. if (res) {
  62284. return res;
  62285. }
  62286. }
  62287. return null;
  62288. };
  62289. return StringDictionary;
  62290. }());
  62291. BABYLON.StringDictionary = StringDictionary;
  62292. })(BABYLON || (BABYLON = {}));
  62293. //# sourceMappingURL=babylon.stringDictionary.js.map
  62294. var BABYLON;
  62295. (function (BABYLON) {
  62296. var Tags = /** @class */ (function () {
  62297. function Tags() {
  62298. }
  62299. Tags.EnableFor = function (obj) {
  62300. obj._tags = obj._tags || {};
  62301. obj.hasTags = function () {
  62302. return Tags.HasTags(obj);
  62303. };
  62304. obj.addTags = function (tagsString) {
  62305. return Tags.AddTagsTo(obj, tagsString);
  62306. };
  62307. obj.removeTags = function (tagsString) {
  62308. return Tags.RemoveTagsFrom(obj, tagsString);
  62309. };
  62310. obj.matchesTagsQuery = function (tagsQuery) {
  62311. return Tags.MatchesQuery(obj, tagsQuery);
  62312. };
  62313. };
  62314. Tags.DisableFor = function (obj) {
  62315. delete obj._tags;
  62316. delete obj.hasTags;
  62317. delete obj.addTags;
  62318. delete obj.removeTags;
  62319. delete obj.matchesTagsQuery;
  62320. };
  62321. Tags.HasTags = function (obj) {
  62322. if (!obj._tags) {
  62323. return false;
  62324. }
  62325. return !BABYLON.Tools.IsEmpty(obj._tags);
  62326. };
  62327. Tags.GetTags = function (obj, asString) {
  62328. if (asString === void 0) { asString = true; }
  62329. if (!obj._tags) {
  62330. return null;
  62331. }
  62332. if (asString) {
  62333. var tagsArray = [];
  62334. for (var tag in obj._tags) {
  62335. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62336. tagsArray.push(tag);
  62337. }
  62338. }
  62339. return tagsArray.join(" ");
  62340. }
  62341. else {
  62342. return obj._tags;
  62343. }
  62344. };
  62345. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62346. // a tag cannot start with '||', '&&', and '!'
  62347. // it cannot contain whitespaces
  62348. Tags.AddTagsTo = function (obj, tagsString) {
  62349. if (!tagsString) {
  62350. return;
  62351. }
  62352. if (typeof tagsString !== "string") {
  62353. return;
  62354. }
  62355. var tags = tagsString.split(" ");
  62356. tags.forEach(function (tag, index, array) {
  62357. Tags._AddTagTo(obj, tag);
  62358. });
  62359. };
  62360. Tags._AddTagTo = function (obj, tag) {
  62361. tag = tag.trim();
  62362. if (tag === "" || tag === "true" || tag === "false") {
  62363. return;
  62364. }
  62365. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62366. return;
  62367. }
  62368. Tags.EnableFor(obj);
  62369. obj._tags[tag] = true;
  62370. };
  62371. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62372. if (!Tags.HasTags(obj)) {
  62373. return;
  62374. }
  62375. var tags = tagsString.split(" ");
  62376. for (var t in tags) {
  62377. Tags._RemoveTagFrom(obj, tags[t]);
  62378. }
  62379. };
  62380. Tags._RemoveTagFrom = function (obj, tag) {
  62381. delete obj._tags[tag];
  62382. };
  62383. Tags.MatchesQuery = function (obj, tagsQuery) {
  62384. if (tagsQuery === undefined) {
  62385. return true;
  62386. }
  62387. if (tagsQuery === "") {
  62388. return Tags.HasTags(obj);
  62389. }
  62390. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62391. };
  62392. return Tags;
  62393. }());
  62394. BABYLON.Tags = Tags;
  62395. })(BABYLON || (BABYLON = {}));
  62396. //# sourceMappingURL=babylon.tags.js.map
  62397. var BABYLON;
  62398. (function (BABYLON) {
  62399. var AndOrNotEvaluator = /** @class */ (function () {
  62400. function AndOrNotEvaluator() {
  62401. }
  62402. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62403. if (!query.match(/\([^\(\)]*\)/g)) {
  62404. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62405. }
  62406. else {
  62407. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62408. // remove parenthesis
  62409. r = r.slice(1, r.length - 1);
  62410. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62411. });
  62412. }
  62413. if (query === "true") {
  62414. return true;
  62415. }
  62416. if (query === "false") {
  62417. return false;
  62418. }
  62419. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62420. };
  62421. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62422. evaluateCallback = evaluateCallback || (function (r) {
  62423. return r === "true" ? true : false;
  62424. });
  62425. var result;
  62426. var or = parenthesisContent.split("||");
  62427. for (var i in or) {
  62428. if (or.hasOwnProperty(i)) {
  62429. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62430. var and = ori.split("&&");
  62431. if (and.length > 1) {
  62432. for (var j = 0; j < and.length; ++j) {
  62433. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62434. if (andj !== "true" && andj !== "false") {
  62435. if (andj[0] === "!") {
  62436. result = !evaluateCallback(andj.substring(1));
  62437. }
  62438. else {
  62439. result = evaluateCallback(andj);
  62440. }
  62441. }
  62442. else {
  62443. result = andj === "true" ? true : false;
  62444. }
  62445. if (!result) {
  62446. ori = "false";
  62447. break;
  62448. }
  62449. }
  62450. }
  62451. if (result || ori === "true") {
  62452. result = true;
  62453. break;
  62454. }
  62455. // result equals false (or undefined)
  62456. if (ori !== "true" && ori !== "false") {
  62457. if (ori[0] === "!") {
  62458. result = !evaluateCallback(ori.substring(1));
  62459. }
  62460. else {
  62461. result = evaluateCallback(ori);
  62462. }
  62463. }
  62464. else {
  62465. result = ori === "true" ? true : false;
  62466. }
  62467. }
  62468. }
  62469. // the whole parenthesis scope is replaced by 'true' or 'false'
  62470. return result ? "true" : "false";
  62471. };
  62472. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62473. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62474. // remove whitespaces
  62475. r = r.replace(/[\s]/g, function () { return ""; });
  62476. return r.length % 2 ? "!" : "";
  62477. });
  62478. booleanString = booleanString.trim();
  62479. if (booleanString === "!true") {
  62480. booleanString = "false";
  62481. }
  62482. else if (booleanString === "!false") {
  62483. booleanString = "true";
  62484. }
  62485. return booleanString;
  62486. };
  62487. return AndOrNotEvaluator;
  62488. }());
  62489. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62490. })(BABYLON || (BABYLON = {}));
  62491. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62492. var BABYLON;
  62493. (function (BABYLON) {
  62494. var Database = /** @class */ (function () {
  62495. function Database(urlToScene, callbackManifestChecked) {
  62496. // Handling various flavors of prefixed version of IndexedDB
  62497. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62498. this.callbackManifestChecked = callbackManifestChecked;
  62499. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62500. this.db = null;
  62501. this._enableSceneOffline = false;
  62502. this._enableTexturesOffline = false;
  62503. this.manifestVersionFound = 0;
  62504. this.mustUpdateRessources = false;
  62505. this.hasReachedQuota = false;
  62506. if (!Database.IDBStorageEnabled) {
  62507. this.callbackManifestChecked(true);
  62508. }
  62509. else {
  62510. this.checkManifestFile();
  62511. }
  62512. }
  62513. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62514. get: function () {
  62515. return this._enableSceneOffline;
  62516. },
  62517. enumerable: true,
  62518. configurable: true
  62519. });
  62520. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62521. get: function () {
  62522. return this._enableTexturesOffline;
  62523. },
  62524. enumerable: true,
  62525. configurable: true
  62526. });
  62527. Database.prototype.checkManifestFile = function () {
  62528. var _this = this;
  62529. var noManifestFile = function () {
  62530. _this._enableSceneOffline = false;
  62531. _this._enableTexturesOffline = false;
  62532. _this.callbackManifestChecked(false);
  62533. };
  62534. var timeStampUsed = false;
  62535. var manifestURL = this.currentSceneUrl + ".manifest";
  62536. var xhr = new XMLHttpRequest();
  62537. if (navigator.onLine) {
  62538. // Adding a timestamp to by-pass browsers' cache
  62539. timeStampUsed = true;
  62540. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62541. }
  62542. xhr.open("GET", manifestURL, true);
  62543. xhr.addEventListener("load", function () {
  62544. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62545. try {
  62546. var manifestFile = JSON.parse(xhr.response);
  62547. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62548. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62549. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62550. _this.manifestVersionFound = manifestFile.version;
  62551. }
  62552. if (_this.callbackManifestChecked) {
  62553. _this.callbackManifestChecked(true);
  62554. }
  62555. }
  62556. catch (ex) {
  62557. noManifestFile();
  62558. }
  62559. }
  62560. else {
  62561. noManifestFile();
  62562. }
  62563. }, false);
  62564. xhr.addEventListener("error", function (event) {
  62565. if (timeStampUsed) {
  62566. timeStampUsed = false;
  62567. // Let's retry without the timeStamp
  62568. // It could fail when coupled with HTML5 Offline API
  62569. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62570. xhr.open("GET", retryManifestURL, true);
  62571. xhr.send();
  62572. }
  62573. else {
  62574. noManifestFile();
  62575. }
  62576. }, false);
  62577. try {
  62578. xhr.send();
  62579. }
  62580. catch (ex) {
  62581. BABYLON.Tools.Error("Error on XHR send request.");
  62582. this.callbackManifestChecked(false);
  62583. }
  62584. };
  62585. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62586. var _this = this;
  62587. var handleError = function () {
  62588. _this.isSupported = false;
  62589. if (errorCallback)
  62590. errorCallback();
  62591. };
  62592. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62593. // Your browser doesn't support IndexedDB
  62594. this.isSupported = false;
  62595. if (errorCallback)
  62596. errorCallback();
  62597. }
  62598. else {
  62599. // If the DB hasn't been opened or created yet
  62600. if (!this.db) {
  62601. this.hasReachedQuota = false;
  62602. this.isSupported = true;
  62603. var request = this.idbFactory.open("babylonjs", 1);
  62604. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62605. request.onerror = function (event) {
  62606. handleError();
  62607. };
  62608. // executes when a version change transaction cannot complete due to other active transactions
  62609. request.onblocked = function (event) {
  62610. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62611. handleError();
  62612. };
  62613. // DB has been opened successfully
  62614. request.onsuccess = function (event) {
  62615. _this.db = request.result;
  62616. successCallback();
  62617. };
  62618. // Initialization of the DB. Creating Scenes & Textures stores
  62619. request.onupgradeneeded = function (event) {
  62620. _this.db = (event.target).result;
  62621. if (_this.db) {
  62622. try {
  62623. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62624. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62625. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62626. }
  62627. catch (ex) {
  62628. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62629. handleError();
  62630. }
  62631. }
  62632. };
  62633. }
  62634. else {
  62635. if (successCallback)
  62636. successCallback();
  62637. }
  62638. }
  62639. };
  62640. Database.prototype.loadImageFromDB = function (url, image) {
  62641. var _this = this;
  62642. var completeURL = Database.ReturnFullUrlLocation(url);
  62643. var saveAndLoadImage = function () {
  62644. if (!_this.hasReachedQuota && _this.db !== null) {
  62645. // the texture is not yet in the DB, let's try to save it
  62646. _this._saveImageIntoDBAsync(completeURL, image);
  62647. }
  62648. else {
  62649. image.src = url;
  62650. }
  62651. };
  62652. if (!this.mustUpdateRessources) {
  62653. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62654. }
  62655. else {
  62656. saveAndLoadImage();
  62657. }
  62658. };
  62659. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62660. if (this.isSupported && this.db !== null) {
  62661. var texture;
  62662. var transaction = this.db.transaction(["textures"]);
  62663. transaction.onabort = function (event) {
  62664. image.src = url;
  62665. };
  62666. transaction.oncomplete = function (event) {
  62667. var blobTextureURL;
  62668. if (texture) {
  62669. var URL = window.URL || window.webkitURL;
  62670. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62671. image.onerror = function () {
  62672. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62673. image.src = url;
  62674. };
  62675. image.src = blobTextureURL;
  62676. }
  62677. else {
  62678. notInDBCallback();
  62679. }
  62680. };
  62681. var getRequest = transaction.objectStore("textures").get(url);
  62682. getRequest.onsuccess = function (event) {
  62683. texture = (event.target).result;
  62684. };
  62685. getRequest.onerror = function (event) {
  62686. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62687. image.src = url;
  62688. };
  62689. }
  62690. else {
  62691. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62692. image.src = url;
  62693. }
  62694. };
  62695. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62696. var _this = this;
  62697. if (this.isSupported) {
  62698. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62699. var generateBlobUrl = function () {
  62700. var blobTextureURL;
  62701. if (blob) {
  62702. var URL = window.URL || window.webkitURL;
  62703. try {
  62704. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62705. }
  62706. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62707. catch (ex) {
  62708. blobTextureURL = URL.createObjectURL(blob);
  62709. }
  62710. }
  62711. if (blobTextureURL) {
  62712. image.src = blobTextureURL;
  62713. }
  62714. };
  62715. if (Database.IsUASupportingBlobStorage) {
  62716. var xhr = new XMLHttpRequest(), blob;
  62717. xhr.open("GET", url, true);
  62718. xhr.responseType = "blob";
  62719. xhr.addEventListener("load", function () {
  62720. if (xhr.status === 200 && _this.db) {
  62721. // Blob as response (XHR2)
  62722. blob = xhr.response;
  62723. var transaction = _this.db.transaction(["textures"], "readwrite");
  62724. // the transaction could abort because of a QuotaExceededError error
  62725. transaction.onabort = function (event) {
  62726. try {
  62727. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62728. var srcElement = (event.srcElement || event.target);
  62729. var error = srcElement.error;
  62730. if (error && error.name === "QuotaExceededError") {
  62731. _this.hasReachedQuota = true;
  62732. }
  62733. }
  62734. catch (ex) { }
  62735. generateBlobUrl();
  62736. };
  62737. transaction.oncomplete = function (event) {
  62738. generateBlobUrl();
  62739. };
  62740. var newTexture = { textureUrl: url, data: blob };
  62741. try {
  62742. // Put the blob into the dabase
  62743. var addRequest = transaction.objectStore("textures").put(newTexture);
  62744. addRequest.onsuccess = function (event) {
  62745. };
  62746. addRequest.onerror = function (event) {
  62747. generateBlobUrl();
  62748. };
  62749. }
  62750. catch (ex) {
  62751. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62752. if (ex.code === 25) {
  62753. Database.IsUASupportingBlobStorage = false;
  62754. }
  62755. image.src = url;
  62756. }
  62757. }
  62758. else {
  62759. image.src = url;
  62760. }
  62761. }, false);
  62762. xhr.addEventListener("error", function (event) {
  62763. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62764. image.src = url;
  62765. }, false);
  62766. xhr.send();
  62767. }
  62768. else {
  62769. image.src = url;
  62770. }
  62771. }
  62772. else {
  62773. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62774. image.src = url;
  62775. }
  62776. };
  62777. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62778. var _this = this;
  62779. var updateVersion = function () {
  62780. // the version is not yet in the DB or we need to update it
  62781. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62782. };
  62783. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62784. };
  62785. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62786. var _this = this;
  62787. if (this.isSupported && this.db) {
  62788. var version;
  62789. try {
  62790. var transaction = this.db.transaction(["versions"]);
  62791. transaction.oncomplete = function (event) {
  62792. if (version) {
  62793. // If the version in the JSON file is > than the version in DB
  62794. if (_this.manifestVersionFound > version.data) {
  62795. _this.mustUpdateRessources = true;
  62796. updateInDBCallback();
  62797. }
  62798. else {
  62799. callback(version.data);
  62800. }
  62801. }
  62802. else {
  62803. _this.mustUpdateRessources = true;
  62804. updateInDBCallback();
  62805. }
  62806. };
  62807. transaction.onabort = function (event) {
  62808. callback(-1);
  62809. };
  62810. var getRequest = transaction.objectStore("versions").get(url);
  62811. getRequest.onsuccess = function (event) {
  62812. version = (event.target).result;
  62813. };
  62814. getRequest.onerror = function (event) {
  62815. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62816. callback(-1);
  62817. };
  62818. }
  62819. catch (ex) {
  62820. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62821. callback(-1);
  62822. }
  62823. }
  62824. else {
  62825. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62826. callback(-1);
  62827. }
  62828. };
  62829. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62830. var _this = this;
  62831. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62832. try {
  62833. // Open a transaction to the database
  62834. var transaction = this.db.transaction(["versions"], "readwrite");
  62835. // the transaction could abort because of a QuotaExceededError error
  62836. transaction.onabort = function (event) {
  62837. try {
  62838. var error = event.srcElement['error'];
  62839. if (error && error.name === "QuotaExceededError") {
  62840. _this.hasReachedQuota = true;
  62841. }
  62842. }
  62843. catch (ex) { }
  62844. callback(-1);
  62845. };
  62846. transaction.oncomplete = function (event) {
  62847. callback(_this.manifestVersionFound);
  62848. };
  62849. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62850. // Put the scene into the database
  62851. var addRequest = transaction.objectStore("versions").put(newVersion);
  62852. addRequest.onsuccess = function (event) {
  62853. };
  62854. addRequest.onerror = function (event) {
  62855. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62856. };
  62857. }
  62858. catch (ex) {
  62859. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62860. callback(-1);
  62861. }
  62862. }
  62863. else {
  62864. callback(-1);
  62865. }
  62866. };
  62867. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62868. var _this = this;
  62869. var completeUrl = Database.ReturnFullUrlLocation(url);
  62870. var saveAndLoadFile = function () {
  62871. // the scene is not yet in the DB, let's try to save it
  62872. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62873. };
  62874. this._checkVersionFromDB(completeUrl, function (version) {
  62875. if (version !== -1) {
  62876. if (!_this.mustUpdateRessources) {
  62877. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62878. }
  62879. else {
  62880. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62881. }
  62882. }
  62883. else {
  62884. if (errorCallback) {
  62885. errorCallback();
  62886. }
  62887. }
  62888. });
  62889. };
  62890. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62891. if (this.isSupported && this.db) {
  62892. var targetStore;
  62893. if (url.indexOf(".babylon") !== -1) {
  62894. targetStore = "scenes";
  62895. }
  62896. else {
  62897. targetStore = "textures";
  62898. }
  62899. var file;
  62900. var transaction = this.db.transaction([targetStore]);
  62901. transaction.oncomplete = function (event) {
  62902. if (file) {
  62903. callback(file.data);
  62904. }
  62905. else {
  62906. notInDBCallback();
  62907. }
  62908. };
  62909. transaction.onabort = function (event) {
  62910. notInDBCallback();
  62911. };
  62912. var getRequest = transaction.objectStore(targetStore).get(url);
  62913. getRequest.onsuccess = function (event) {
  62914. file = (event.target).result;
  62915. };
  62916. getRequest.onerror = function (event) {
  62917. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62918. notInDBCallback();
  62919. };
  62920. }
  62921. else {
  62922. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62923. callback();
  62924. }
  62925. };
  62926. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62927. var _this = this;
  62928. if (this.isSupported) {
  62929. var targetStore;
  62930. if (url.indexOf(".babylon") !== -1) {
  62931. targetStore = "scenes";
  62932. }
  62933. else {
  62934. targetStore = "textures";
  62935. }
  62936. // Create XHR
  62937. var xhr = new XMLHttpRequest();
  62938. var fileData;
  62939. xhr.open("GET", url, true);
  62940. if (useArrayBuffer) {
  62941. xhr.responseType = "arraybuffer";
  62942. }
  62943. if (progressCallback) {
  62944. xhr.onprogress = progressCallback;
  62945. }
  62946. xhr.addEventListener("load", function () {
  62947. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62948. // Blob as response (XHR2)
  62949. //fileData = xhr.responseText;
  62950. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62951. if (!_this.hasReachedQuota && _this.db) {
  62952. // Open a transaction to the database
  62953. var transaction = _this.db.transaction([targetStore], "readwrite");
  62954. // the transaction could abort because of a QuotaExceededError error
  62955. transaction.onabort = function (event) {
  62956. try {
  62957. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62958. var error = event.srcElement['error'];
  62959. if (error && error.name === "QuotaExceededError") {
  62960. _this.hasReachedQuota = true;
  62961. }
  62962. }
  62963. catch (ex) { }
  62964. callback(fileData);
  62965. };
  62966. transaction.oncomplete = function (event) {
  62967. callback(fileData);
  62968. };
  62969. var newFile;
  62970. if (targetStore === "scenes") {
  62971. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62972. }
  62973. else {
  62974. newFile = { textureUrl: url, data: fileData };
  62975. }
  62976. try {
  62977. // Put the scene into the database
  62978. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62979. addRequest.onsuccess = function (event) {
  62980. };
  62981. addRequest.onerror = function (event) {
  62982. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62983. };
  62984. }
  62985. catch (ex) {
  62986. callback(fileData);
  62987. }
  62988. }
  62989. else {
  62990. callback(fileData);
  62991. }
  62992. }
  62993. else {
  62994. callback();
  62995. }
  62996. }, false);
  62997. xhr.addEventListener("error", function (event) {
  62998. BABYLON.Tools.Error("error on XHR request.");
  62999. callback();
  63000. }, false);
  63001. xhr.send();
  63002. }
  63003. else {
  63004. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63005. callback();
  63006. }
  63007. };
  63008. Database.IsUASupportingBlobStorage = true;
  63009. Database.IDBStorageEnabled = true;
  63010. Database.parseURL = function (url) {
  63011. var a = document.createElement('a');
  63012. a.href = url;
  63013. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63014. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63015. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63016. return absLocation;
  63017. };
  63018. Database.ReturnFullUrlLocation = function (url) {
  63019. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63020. return (Database.parseURL(window.location.href) + url);
  63021. }
  63022. else {
  63023. return url;
  63024. }
  63025. };
  63026. return Database;
  63027. }());
  63028. BABYLON.Database = Database;
  63029. })(BABYLON || (BABYLON = {}));
  63030. //# sourceMappingURL=babylon.database.js.map
  63031. var BABYLON;
  63032. (function (BABYLON) {
  63033. var FresnelParameters = /** @class */ (function () {
  63034. function FresnelParameters() {
  63035. this._isEnabled = true;
  63036. this.leftColor = BABYLON.Color3.White();
  63037. this.rightColor = BABYLON.Color3.Black();
  63038. this.bias = 0;
  63039. this.power = 1;
  63040. }
  63041. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63042. get: function () {
  63043. return this._isEnabled;
  63044. },
  63045. set: function (value) {
  63046. if (this._isEnabled === value) {
  63047. return;
  63048. }
  63049. this._isEnabled = value;
  63050. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63051. },
  63052. enumerable: true,
  63053. configurable: true
  63054. });
  63055. FresnelParameters.prototype.clone = function () {
  63056. var newFresnelParameters = new FresnelParameters();
  63057. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63058. return newFresnelParameters;
  63059. };
  63060. FresnelParameters.prototype.serialize = function () {
  63061. var serializationObject = {};
  63062. serializationObject.isEnabled = this.isEnabled;
  63063. serializationObject.leftColor = this.leftColor;
  63064. serializationObject.rightColor = this.rightColor;
  63065. serializationObject.bias = this.bias;
  63066. serializationObject.power = this.power;
  63067. return serializationObject;
  63068. };
  63069. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63070. var fresnelParameters = new FresnelParameters();
  63071. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63072. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63073. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63074. fresnelParameters.bias = parsedFresnelParameters.bias;
  63075. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63076. return fresnelParameters;
  63077. };
  63078. return FresnelParameters;
  63079. }());
  63080. BABYLON.FresnelParameters = FresnelParameters;
  63081. })(BABYLON || (BABYLON = {}));
  63082. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63083. var BABYLON;
  63084. (function (BABYLON) {
  63085. var MultiMaterial = /** @class */ (function (_super) {
  63086. __extends(MultiMaterial, _super);
  63087. function MultiMaterial(name, scene) {
  63088. var _this = _super.call(this, name, scene, true) || this;
  63089. scene.multiMaterials.push(_this);
  63090. _this.subMaterials = new Array();
  63091. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63092. return _this;
  63093. }
  63094. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63095. get: function () {
  63096. return this._subMaterials;
  63097. },
  63098. set: function (value) {
  63099. this._subMaterials = value;
  63100. this._hookArray(value);
  63101. },
  63102. enumerable: true,
  63103. configurable: true
  63104. });
  63105. MultiMaterial.prototype._hookArray = function (array) {
  63106. var _this = this;
  63107. var oldPush = array.push;
  63108. array.push = function () {
  63109. var items = [];
  63110. for (var _i = 0; _i < arguments.length; _i++) {
  63111. items[_i] = arguments[_i];
  63112. }
  63113. var result = oldPush.apply(array, items);
  63114. _this._markAllSubMeshesAsTexturesDirty();
  63115. return result;
  63116. };
  63117. var oldSplice = array.splice;
  63118. array.splice = function (index, deleteCount) {
  63119. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63120. _this._markAllSubMeshesAsTexturesDirty();
  63121. return deleted;
  63122. };
  63123. };
  63124. // Properties
  63125. MultiMaterial.prototype.getSubMaterial = function (index) {
  63126. if (index < 0 || index >= this.subMaterials.length) {
  63127. return this.getScene().defaultMaterial;
  63128. }
  63129. return this.subMaterials[index];
  63130. };
  63131. MultiMaterial.prototype.getActiveTextures = function () {
  63132. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63133. if (subMaterial) {
  63134. return subMaterial.getActiveTextures();
  63135. }
  63136. else {
  63137. return [];
  63138. }
  63139. }));
  63140. var _a;
  63141. };
  63142. // Methods
  63143. MultiMaterial.prototype.getClassName = function () {
  63144. return "MultiMaterial";
  63145. };
  63146. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63147. for (var index = 0; index < this.subMaterials.length; index++) {
  63148. var subMaterial = this.subMaterials[index];
  63149. if (subMaterial) {
  63150. if (subMaterial.storeEffectOnSubMeshes) {
  63151. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63152. return false;
  63153. }
  63154. continue;
  63155. }
  63156. if (!subMaterial.isReady(mesh)) {
  63157. return false;
  63158. }
  63159. }
  63160. }
  63161. return true;
  63162. };
  63163. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63164. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63165. for (var index = 0; index < this.subMaterials.length; index++) {
  63166. var subMaterial = null;
  63167. var current = this.subMaterials[index];
  63168. if (cloneChildren && current) {
  63169. subMaterial = current.clone(name + "-" + current.name);
  63170. }
  63171. else {
  63172. subMaterial = this.subMaterials[index];
  63173. }
  63174. newMultiMaterial.subMaterials.push(subMaterial);
  63175. }
  63176. return newMultiMaterial;
  63177. };
  63178. MultiMaterial.prototype.serialize = function () {
  63179. var serializationObject = {};
  63180. serializationObject.name = this.name;
  63181. serializationObject.id = this.id;
  63182. if (BABYLON.Tags) {
  63183. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63184. }
  63185. serializationObject.materials = [];
  63186. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63187. var subMat = this.subMaterials[matIndex];
  63188. if (subMat) {
  63189. serializationObject.materials.push(subMat.id);
  63190. }
  63191. else {
  63192. serializationObject.materials.push(null);
  63193. }
  63194. }
  63195. return serializationObject;
  63196. };
  63197. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63198. var scene = this.getScene();
  63199. if (!scene) {
  63200. return;
  63201. }
  63202. var index = scene.multiMaterials.indexOf(this);
  63203. if (index >= 0) {
  63204. scene.multiMaterials.splice(index, 1);
  63205. }
  63206. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63207. };
  63208. return MultiMaterial;
  63209. }(BABYLON.Material));
  63210. BABYLON.MultiMaterial = MultiMaterial;
  63211. })(BABYLON || (BABYLON = {}));
  63212. //# sourceMappingURL=babylon.multiMaterial.js.map
  63213. var BABYLON;
  63214. (function (BABYLON) {
  63215. var FreeCameraTouchInput = /** @class */ (function () {
  63216. function FreeCameraTouchInput() {
  63217. this._offsetX = null;
  63218. this._offsetY = null;
  63219. this._pointerPressed = new Array();
  63220. this.touchAngularSensibility = 200000.0;
  63221. this.touchMoveSensibility = 250.0;
  63222. }
  63223. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63224. var _this = this;
  63225. var previousPosition = null;
  63226. if (this._pointerInput === undefined) {
  63227. this._onLostFocus = function (evt) {
  63228. _this._offsetX = null;
  63229. _this._offsetY = null;
  63230. };
  63231. this._pointerInput = function (p, s) {
  63232. var evt = p.event;
  63233. if (evt.pointerType === "mouse") {
  63234. return;
  63235. }
  63236. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63237. if (!noPreventDefault) {
  63238. evt.preventDefault();
  63239. }
  63240. _this._pointerPressed.push(evt.pointerId);
  63241. if (_this._pointerPressed.length !== 1) {
  63242. return;
  63243. }
  63244. previousPosition = {
  63245. x: evt.clientX,
  63246. y: evt.clientY
  63247. };
  63248. }
  63249. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63250. if (!noPreventDefault) {
  63251. evt.preventDefault();
  63252. }
  63253. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63254. if (index === -1) {
  63255. return;
  63256. }
  63257. _this._pointerPressed.splice(index, 1);
  63258. if (index != 0) {
  63259. return;
  63260. }
  63261. previousPosition = null;
  63262. _this._offsetX = null;
  63263. _this._offsetY = null;
  63264. }
  63265. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63266. if (!noPreventDefault) {
  63267. evt.preventDefault();
  63268. }
  63269. if (!previousPosition) {
  63270. return;
  63271. }
  63272. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63273. if (index != 0) {
  63274. return;
  63275. }
  63276. _this._offsetX = evt.clientX - previousPosition.x;
  63277. _this._offsetY = -(evt.clientY - previousPosition.y);
  63278. }
  63279. };
  63280. }
  63281. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63282. if (this._onLostFocus) {
  63283. element.addEventListener("blur", this._onLostFocus);
  63284. }
  63285. };
  63286. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63287. if (this._pointerInput && element) {
  63288. if (this._observer) {
  63289. this.camera.getScene().onPointerObservable.remove(this._observer);
  63290. this._observer = null;
  63291. }
  63292. if (this._onLostFocus) {
  63293. element.removeEventListener("blur", this._onLostFocus);
  63294. this._onLostFocus = null;
  63295. }
  63296. this._pointerPressed = [];
  63297. this._offsetX = null;
  63298. this._offsetY = null;
  63299. }
  63300. };
  63301. FreeCameraTouchInput.prototype.checkInputs = function () {
  63302. if (this._offsetX && this._offsetY) {
  63303. var camera = this.camera;
  63304. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63305. if (this._pointerPressed.length > 1) {
  63306. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63307. }
  63308. else {
  63309. var speed = camera._computeLocalCameraSpeed();
  63310. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63311. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63312. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63313. }
  63314. }
  63315. };
  63316. FreeCameraTouchInput.prototype.getClassName = function () {
  63317. return "FreeCameraTouchInput";
  63318. };
  63319. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63320. return "touch";
  63321. };
  63322. __decorate([
  63323. BABYLON.serialize()
  63324. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63325. __decorate([
  63326. BABYLON.serialize()
  63327. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63328. return FreeCameraTouchInput;
  63329. }());
  63330. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63331. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63332. })(BABYLON || (BABYLON = {}));
  63333. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63334. var BABYLON;
  63335. (function (BABYLON) {
  63336. // We're mainly based on the logic defined into the FreeCamera code
  63337. var TouchCamera = /** @class */ (function (_super) {
  63338. __extends(TouchCamera, _super);
  63339. //-- end properties for backward compatibility for inputs
  63340. function TouchCamera(name, position, scene) {
  63341. var _this = _super.call(this, name, position, scene) || this;
  63342. _this.inputs.addTouch();
  63343. _this._setupInputs();
  63344. return _this;
  63345. }
  63346. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63347. //-- Begin properties for backward compatibility for inputs
  63348. get: function () {
  63349. var touch = this.inputs.attached["touch"];
  63350. if (touch)
  63351. return touch.touchAngularSensibility;
  63352. return 0;
  63353. },
  63354. set: function (value) {
  63355. var touch = this.inputs.attached["touch"];
  63356. if (touch)
  63357. touch.touchAngularSensibility = value;
  63358. },
  63359. enumerable: true,
  63360. configurable: true
  63361. });
  63362. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63363. get: function () {
  63364. var touch = this.inputs.attached["touch"];
  63365. if (touch)
  63366. return touch.touchMoveSensibility;
  63367. return 0;
  63368. },
  63369. set: function (value) {
  63370. var touch = this.inputs.attached["touch"];
  63371. if (touch)
  63372. touch.touchMoveSensibility = value;
  63373. },
  63374. enumerable: true,
  63375. configurable: true
  63376. });
  63377. TouchCamera.prototype.getClassName = function () {
  63378. return "TouchCamera";
  63379. };
  63380. TouchCamera.prototype._setupInputs = function () {
  63381. var mouse = this.inputs.attached["mouse"];
  63382. if (mouse) {
  63383. mouse.touchEnabled = false;
  63384. }
  63385. };
  63386. return TouchCamera;
  63387. }(BABYLON.FreeCamera));
  63388. BABYLON.TouchCamera = TouchCamera;
  63389. })(BABYLON || (BABYLON = {}));
  63390. //# sourceMappingURL=babylon.touchCamera.js.map
  63391. var BABYLON;
  63392. (function (BABYLON) {
  63393. var ProceduralTexture = /** @class */ (function (_super) {
  63394. __extends(ProceduralTexture, _super);
  63395. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63396. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63397. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63398. if (isCube === void 0) { isCube = false; }
  63399. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63400. _this.isCube = isCube;
  63401. _this.isEnabled = true;
  63402. _this._currentRefreshId = -1;
  63403. _this._refreshRate = 1;
  63404. _this._vertexBuffers = {};
  63405. _this._uniforms = new Array();
  63406. _this._samplers = new Array();
  63407. _this._textures = {};
  63408. _this._floats = {};
  63409. _this._floatsArrays = {};
  63410. _this._colors3 = {};
  63411. _this._colors4 = {};
  63412. _this._vectors2 = {};
  63413. _this._vectors3 = {};
  63414. _this._matrices = {};
  63415. _this._fallbackTextureUsed = false;
  63416. scene._proceduralTextures.push(_this);
  63417. _this._engine = scene.getEngine();
  63418. _this.name = name;
  63419. _this.isRenderTarget = true;
  63420. _this._size = size;
  63421. _this._generateMipMaps = generateMipMaps;
  63422. _this.setFragment(fragment);
  63423. _this._fallbackTexture = fallbackTexture;
  63424. if (isCube) {
  63425. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63426. _this.setFloat("face", 0);
  63427. }
  63428. else {
  63429. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63430. }
  63431. // VBO
  63432. var vertices = [];
  63433. vertices.push(1, 1);
  63434. vertices.push(-1, 1);
  63435. vertices.push(-1, -1);
  63436. vertices.push(1, -1);
  63437. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63438. _this._createIndexBuffer();
  63439. return _this;
  63440. }
  63441. ProceduralTexture.prototype._createIndexBuffer = function () {
  63442. var engine = this._engine;
  63443. // Indices
  63444. var indices = [];
  63445. indices.push(0);
  63446. indices.push(1);
  63447. indices.push(2);
  63448. indices.push(0);
  63449. indices.push(2);
  63450. indices.push(3);
  63451. this._indexBuffer = engine.createIndexBuffer(indices);
  63452. };
  63453. ProceduralTexture.prototype._rebuild = function () {
  63454. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63455. if (vb) {
  63456. vb._rebuild();
  63457. }
  63458. this._createIndexBuffer();
  63459. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63460. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63461. }
  63462. };
  63463. ProceduralTexture.prototype.reset = function () {
  63464. if (this._effect === undefined) {
  63465. return;
  63466. }
  63467. var engine = this._engine;
  63468. engine._releaseEffect(this._effect);
  63469. };
  63470. ProceduralTexture.prototype.isReady = function () {
  63471. var _this = this;
  63472. var engine = this._engine;
  63473. var shaders;
  63474. if (!this._fragment) {
  63475. return false;
  63476. }
  63477. if (this._fallbackTextureUsed) {
  63478. return true;
  63479. }
  63480. if (this._fragment.fragmentElement !== undefined) {
  63481. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63482. }
  63483. else {
  63484. shaders = { vertex: "procedural", fragment: this._fragment };
  63485. }
  63486. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63487. _this.releaseInternalTexture();
  63488. if (_this._fallbackTexture) {
  63489. _this._texture = _this._fallbackTexture._texture;
  63490. if (_this._texture) {
  63491. _this._texture.incrementReferences();
  63492. }
  63493. }
  63494. _this._fallbackTextureUsed = true;
  63495. });
  63496. return this._effect.isReady();
  63497. };
  63498. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63499. this._currentRefreshId = -1;
  63500. };
  63501. ProceduralTexture.prototype.setFragment = function (fragment) {
  63502. this._fragment = fragment;
  63503. };
  63504. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63505. get: function () {
  63506. return this._refreshRate;
  63507. },
  63508. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63509. set: function (value) {
  63510. this._refreshRate = value;
  63511. this.resetRefreshCounter();
  63512. },
  63513. enumerable: true,
  63514. configurable: true
  63515. });
  63516. ProceduralTexture.prototype._shouldRender = function () {
  63517. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63518. return false;
  63519. }
  63520. if (this._fallbackTextureUsed) {
  63521. return false;
  63522. }
  63523. if (this._currentRefreshId === -1) {
  63524. this._currentRefreshId = 1;
  63525. return true;
  63526. }
  63527. if (this.refreshRate === this._currentRefreshId) {
  63528. this._currentRefreshId = 1;
  63529. return true;
  63530. }
  63531. this._currentRefreshId++;
  63532. return false;
  63533. };
  63534. ProceduralTexture.prototype.getRenderSize = function () {
  63535. return this._size;
  63536. };
  63537. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63538. if (this._fallbackTextureUsed) {
  63539. return;
  63540. }
  63541. this.releaseInternalTexture();
  63542. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63543. };
  63544. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63545. if (this._uniforms.indexOf(uniformName) === -1) {
  63546. this._uniforms.push(uniformName);
  63547. }
  63548. };
  63549. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63550. if (this._samplers.indexOf(name) === -1) {
  63551. this._samplers.push(name);
  63552. }
  63553. this._textures[name] = texture;
  63554. return this;
  63555. };
  63556. ProceduralTexture.prototype.setFloat = function (name, value) {
  63557. this._checkUniform(name);
  63558. this._floats[name] = value;
  63559. return this;
  63560. };
  63561. ProceduralTexture.prototype.setFloats = function (name, value) {
  63562. this._checkUniform(name);
  63563. this._floatsArrays[name] = value;
  63564. return this;
  63565. };
  63566. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63567. this._checkUniform(name);
  63568. this._colors3[name] = value;
  63569. return this;
  63570. };
  63571. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63572. this._checkUniform(name);
  63573. this._colors4[name] = value;
  63574. return this;
  63575. };
  63576. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63577. this._checkUniform(name);
  63578. this._vectors2[name] = value;
  63579. return this;
  63580. };
  63581. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63582. this._checkUniform(name);
  63583. this._vectors3[name] = value;
  63584. return this;
  63585. };
  63586. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63587. this._checkUniform(name);
  63588. this._matrices[name] = value;
  63589. return this;
  63590. };
  63591. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63592. var scene = this.getScene();
  63593. if (!scene) {
  63594. return;
  63595. }
  63596. var engine = this._engine;
  63597. // Render
  63598. engine.enableEffect(this._effect);
  63599. engine.setState(false);
  63600. // Texture
  63601. for (var name in this._textures) {
  63602. this._effect.setTexture(name, this._textures[name]);
  63603. }
  63604. // Float
  63605. for (name in this._floats) {
  63606. this._effect.setFloat(name, this._floats[name]);
  63607. }
  63608. // Floats
  63609. for (name in this._floatsArrays) {
  63610. this._effect.setArray(name, this._floatsArrays[name]);
  63611. }
  63612. // Color3
  63613. for (name in this._colors3) {
  63614. this._effect.setColor3(name, this._colors3[name]);
  63615. }
  63616. // Color4
  63617. for (name in this._colors4) {
  63618. var color = this._colors4[name];
  63619. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63620. }
  63621. // Vector2
  63622. for (name in this._vectors2) {
  63623. this._effect.setVector2(name, this._vectors2[name]);
  63624. }
  63625. // Vector3
  63626. for (name in this._vectors3) {
  63627. this._effect.setVector3(name, this._vectors3[name]);
  63628. }
  63629. // Matrix
  63630. for (name in this._matrices) {
  63631. this._effect.setMatrix(name, this._matrices[name]);
  63632. }
  63633. if (!this._texture) {
  63634. return;
  63635. }
  63636. if (this.isCube) {
  63637. for (var face = 0; face < 6; face++) {
  63638. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63639. // VBOs
  63640. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63641. this._effect.setFloat("face", face);
  63642. // Clear
  63643. engine.clear(scene.clearColor, true, true, true);
  63644. // Draw order
  63645. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63646. // Mipmaps
  63647. if (face === 5) {
  63648. engine.generateMipMapsForCubemap(this._texture);
  63649. }
  63650. }
  63651. }
  63652. else {
  63653. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63654. // VBOs
  63655. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63656. // Clear
  63657. engine.clear(scene.clearColor, true, true, true);
  63658. // Draw order
  63659. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63660. }
  63661. // Unbind
  63662. engine.unBindFramebuffer(this._texture, this.isCube);
  63663. if (this.onGenerated) {
  63664. this.onGenerated();
  63665. }
  63666. };
  63667. ProceduralTexture.prototype.clone = function () {
  63668. var textureSize = this.getSize();
  63669. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63670. // Base texture
  63671. newTexture.hasAlpha = this.hasAlpha;
  63672. newTexture.level = this.level;
  63673. // RenderTarget Texture
  63674. newTexture.coordinatesMode = this.coordinatesMode;
  63675. return newTexture;
  63676. };
  63677. ProceduralTexture.prototype.dispose = function () {
  63678. var scene = this.getScene();
  63679. if (!scene) {
  63680. return;
  63681. }
  63682. var index = scene._proceduralTextures.indexOf(this);
  63683. if (index >= 0) {
  63684. scene._proceduralTextures.splice(index, 1);
  63685. }
  63686. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63687. if (vertexBuffer) {
  63688. vertexBuffer.dispose();
  63689. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63690. }
  63691. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63692. this._indexBuffer = null;
  63693. }
  63694. _super.prototype.dispose.call(this);
  63695. };
  63696. return ProceduralTexture;
  63697. }(BABYLON.Texture));
  63698. BABYLON.ProceduralTexture = ProceduralTexture;
  63699. })(BABYLON || (BABYLON = {}));
  63700. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63701. var BABYLON;
  63702. (function (BABYLON) {
  63703. var CustomProceduralTexture = /** @class */ (function (_super) {
  63704. __extends(CustomProceduralTexture, _super);
  63705. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63706. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63707. _this._animate = true;
  63708. _this._time = 0;
  63709. _this._texturePath = texturePath;
  63710. //Try to load json
  63711. _this.loadJson(texturePath);
  63712. _this.refreshRate = 1;
  63713. return _this;
  63714. }
  63715. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63716. var _this = this;
  63717. var noConfigFile = function () {
  63718. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63719. try {
  63720. _this.setFragment(_this._texturePath);
  63721. }
  63722. catch (ex) {
  63723. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63724. }
  63725. };
  63726. var configFileUrl = jsonUrl + "/config.json";
  63727. var xhr = new XMLHttpRequest();
  63728. xhr.open("GET", configFileUrl, true);
  63729. xhr.addEventListener("load", function () {
  63730. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63731. try {
  63732. _this._config = JSON.parse(xhr.response);
  63733. _this.updateShaderUniforms();
  63734. _this.updateTextures();
  63735. _this.setFragment(_this._texturePath + "/custom");
  63736. _this._animate = _this._config.animate;
  63737. _this.refreshRate = _this._config.refreshrate;
  63738. }
  63739. catch (ex) {
  63740. noConfigFile();
  63741. }
  63742. }
  63743. else {
  63744. noConfigFile();
  63745. }
  63746. }, false);
  63747. xhr.addEventListener("error", function () {
  63748. noConfigFile();
  63749. }, false);
  63750. try {
  63751. xhr.send();
  63752. }
  63753. catch (ex) {
  63754. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63755. }
  63756. };
  63757. CustomProceduralTexture.prototype.isReady = function () {
  63758. if (!_super.prototype.isReady.call(this)) {
  63759. return false;
  63760. }
  63761. for (var name in this._textures) {
  63762. var texture = this._textures[name];
  63763. if (!texture.isReady()) {
  63764. return false;
  63765. }
  63766. }
  63767. return true;
  63768. };
  63769. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63770. var scene = this.getScene();
  63771. if (this._animate && scene) {
  63772. this._time += scene.getAnimationRatio() * 0.03;
  63773. this.updateShaderUniforms();
  63774. }
  63775. _super.prototype.render.call(this, useCameraPostProcess);
  63776. };
  63777. CustomProceduralTexture.prototype.updateTextures = function () {
  63778. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63779. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63780. }
  63781. };
  63782. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63783. if (this._config) {
  63784. for (var j = 0; j < this._config.uniforms.length; j++) {
  63785. var uniform = this._config.uniforms[j];
  63786. switch (uniform.type) {
  63787. case "float":
  63788. this.setFloat(uniform.name, uniform.value);
  63789. break;
  63790. case "color3":
  63791. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63792. break;
  63793. case "color4":
  63794. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63795. break;
  63796. case "vector2":
  63797. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63798. break;
  63799. case "vector3":
  63800. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63801. break;
  63802. }
  63803. }
  63804. }
  63805. this.setFloat("time", this._time);
  63806. };
  63807. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63808. get: function () {
  63809. return this._animate;
  63810. },
  63811. set: function (value) {
  63812. this._animate = value;
  63813. },
  63814. enumerable: true,
  63815. configurable: true
  63816. });
  63817. return CustomProceduralTexture;
  63818. }(BABYLON.ProceduralTexture));
  63819. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63820. })(BABYLON || (BABYLON = {}));
  63821. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63822. var BABYLON;
  63823. (function (BABYLON) {
  63824. var FreeCameraGamepadInput = /** @class */ (function () {
  63825. function FreeCameraGamepadInput() {
  63826. this.gamepadAngularSensibility = 200;
  63827. this.gamepadMoveSensibility = 40;
  63828. // private members
  63829. this._cameraTransform = BABYLON.Matrix.Identity();
  63830. this._deltaTransform = BABYLON.Vector3.Zero();
  63831. this._vector3 = BABYLON.Vector3.Zero();
  63832. this._vector2 = BABYLON.Vector2.Zero();
  63833. }
  63834. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63835. var _this = this;
  63836. var manager = this.camera.getScene().gamepadManager;
  63837. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63838. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63839. // prioritize XBOX gamepads.
  63840. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63841. _this.gamepad = gamepad;
  63842. }
  63843. }
  63844. });
  63845. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63846. if (_this.gamepad === gamepad) {
  63847. _this.gamepad = null;
  63848. }
  63849. });
  63850. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63851. };
  63852. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63853. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63854. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63855. this.gamepad = null;
  63856. };
  63857. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63858. if (this.gamepad && this.gamepad.leftStick) {
  63859. var camera = this.camera;
  63860. var LSValues = this.gamepad.leftStick;
  63861. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63862. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63863. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63864. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63865. var RSValues = this.gamepad.rightStick;
  63866. if (RSValues) {
  63867. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63868. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63869. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63870. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63871. }
  63872. else {
  63873. RSValues = { x: 0, y: 0 };
  63874. }
  63875. if (!camera.rotationQuaternion) {
  63876. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63877. }
  63878. else {
  63879. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63880. }
  63881. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63882. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63883. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63884. camera.cameraDirection.addInPlace(this._deltaTransform);
  63885. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63886. camera.cameraRotation.addInPlace(this._vector2);
  63887. }
  63888. };
  63889. FreeCameraGamepadInput.prototype.getClassName = function () {
  63890. return "FreeCameraGamepadInput";
  63891. };
  63892. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63893. return "gamepad";
  63894. };
  63895. __decorate([
  63896. BABYLON.serialize()
  63897. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63898. __decorate([
  63899. BABYLON.serialize()
  63900. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63901. return FreeCameraGamepadInput;
  63902. }());
  63903. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63904. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63905. })(BABYLON || (BABYLON = {}));
  63906. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63907. var BABYLON;
  63908. (function (BABYLON) {
  63909. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63910. function ArcRotateCameraGamepadInput() {
  63911. this.gamepadRotationSensibility = 80;
  63912. this.gamepadMoveSensibility = 40;
  63913. }
  63914. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63915. var _this = this;
  63916. var manager = this.camera.getScene().gamepadManager;
  63917. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63918. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63919. // prioritize XBOX gamepads.
  63920. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63921. _this.gamepad = gamepad;
  63922. }
  63923. }
  63924. });
  63925. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63926. if (_this.gamepad === gamepad) {
  63927. _this.gamepad = null;
  63928. }
  63929. });
  63930. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63931. };
  63932. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63933. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63934. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63935. this.gamepad = null;
  63936. };
  63937. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63938. if (this.gamepad) {
  63939. var camera = this.camera;
  63940. var RSValues = this.gamepad.rightStick;
  63941. if (RSValues) {
  63942. if (RSValues.x != 0) {
  63943. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63944. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63945. camera.inertialAlphaOffset += normalizedRX;
  63946. }
  63947. }
  63948. if (RSValues.y != 0) {
  63949. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63950. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63951. camera.inertialBetaOffset += normalizedRY;
  63952. }
  63953. }
  63954. }
  63955. var LSValues = this.gamepad.leftStick;
  63956. if (LSValues && LSValues.y != 0) {
  63957. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63958. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63959. this.camera.inertialRadiusOffset -= normalizedLY;
  63960. }
  63961. }
  63962. }
  63963. };
  63964. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63965. return "ArcRotateCameraGamepadInput";
  63966. };
  63967. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63968. return "gamepad";
  63969. };
  63970. __decorate([
  63971. BABYLON.serialize()
  63972. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63973. __decorate([
  63974. BABYLON.serialize()
  63975. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63976. return ArcRotateCameraGamepadInput;
  63977. }());
  63978. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63979. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63980. })(BABYLON || (BABYLON = {}));
  63981. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63982. var BABYLON;
  63983. (function (BABYLON) {
  63984. var GamepadManager = /** @class */ (function () {
  63985. function GamepadManager(_scene) {
  63986. var _this = this;
  63987. this._scene = _scene;
  63988. this._babylonGamepads = [];
  63989. this._oneGamepadConnected = false;
  63990. this._isMonitoring = false;
  63991. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63992. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63993. this._gamepadEventSupported = false;
  63994. }
  63995. else {
  63996. this._gamepadEventSupported = 'GamepadEvent' in window;
  63997. this._gamepadSupport = (navigator.getGamepads ||
  63998. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63999. }
  64000. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64001. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64002. for (var i in _this._babylonGamepads) {
  64003. var gamepad = _this._babylonGamepads[i];
  64004. if (gamepad && gamepad._isConnected) {
  64005. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64006. }
  64007. }
  64008. });
  64009. this._onGamepadConnectedEvent = function (evt) {
  64010. var gamepad = evt.gamepad;
  64011. if (gamepad.index in _this._babylonGamepads) {
  64012. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64013. return;
  64014. }
  64015. }
  64016. var newGamepad;
  64017. if (_this._babylonGamepads[gamepad.index]) {
  64018. newGamepad = _this._babylonGamepads[gamepad.index];
  64019. newGamepad.browserGamepad = gamepad;
  64020. newGamepad._isConnected = true;
  64021. }
  64022. else {
  64023. newGamepad = _this._addNewGamepad(gamepad);
  64024. }
  64025. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64026. _this._startMonitoringGamepads();
  64027. };
  64028. this._onGamepadDisconnectedEvent = function (evt) {
  64029. var gamepad = evt.gamepad;
  64030. // Remove the gamepad from the list of gamepads to monitor.
  64031. for (var i in _this._babylonGamepads) {
  64032. if (_this._babylonGamepads[i].index === gamepad.index) {
  64033. var disconnectedGamepad = _this._babylonGamepads[i];
  64034. disconnectedGamepad._isConnected = false;
  64035. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64036. break;
  64037. }
  64038. }
  64039. };
  64040. if (this._gamepadSupport) {
  64041. //first add already-connected gamepads
  64042. this._updateGamepadObjects();
  64043. if (this._babylonGamepads.length) {
  64044. this._startMonitoringGamepads();
  64045. }
  64046. // Checking if the gamepad connected event is supported (like in Firefox)
  64047. if (this._gamepadEventSupported) {
  64048. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64049. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64050. }
  64051. else {
  64052. this._startMonitoringGamepads();
  64053. }
  64054. }
  64055. }
  64056. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64057. get: function () {
  64058. return this._babylonGamepads;
  64059. },
  64060. enumerable: true,
  64061. configurable: true
  64062. });
  64063. GamepadManager.prototype.getGamepadByType = function (type) {
  64064. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64065. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64066. var gamepad = _a[_i];
  64067. if (gamepad && gamepad.type === type) {
  64068. return gamepad;
  64069. }
  64070. }
  64071. return null;
  64072. };
  64073. GamepadManager.prototype.dispose = function () {
  64074. if (this._gamepadEventSupported) {
  64075. if (this._onGamepadConnectedEvent) {
  64076. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64077. }
  64078. if (this._onGamepadDisconnectedEvent) {
  64079. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64080. }
  64081. this._onGamepadConnectedEvent = null;
  64082. this._onGamepadDisconnectedEvent = null;
  64083. }
  64084. this._babylonGamepads.forEach(function (gamepad) {
  64085. gamepad.dispose();
  64086. });
  64087. this.onGamepadConnectedObservable.clear();
  64088. this.onGamepadDisconnectedObservable.clear();
  64089. this._oneGamepadConnected = false;
  64090. this._stopMonitoringGamepads();
  64091. this._babylonGamepads = [];
  64092. };
  64093. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64094. if (!this._oneGamepadConnected) {
  64095. this._oneGamepadConnected = true;
  64096. }
  64097. var newGamepad;
  64098. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64099. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64100. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64101. }
  64102. else if (gamepad.pose) {
  64103. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64104. }
  64105. else {
  64106. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64107. }
  64108. this._babylonGamepads[newGamepad.index] = newGamepad;
  64109. return newGamepad;
  64110. };
  64111. GamepadManager.prototype._startMonitoringGamepads = function () {
  64112. if (!this._isMonitoring) {
  64113. this._isMonitoring = true;
  64114. //back-comp
  64115. if (!this._scene) {
  64116. this._checkGamepadsStatus();
  64117. }
  64118. }
  64119. };
  64120. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64121. this._isMonitoring = false;
  64122. };
  64123. GamepadManager.prototype._checkGamepadsStatus = function () {
  64124. var _this = this;
  64125. // Hack to be compatible Chrome
  64126. this._updateGamepadObjects();
  64127. for (var i in this._babylonGamepads) {
  64128. var gamepad = this._babylonGamepads[i];
  64129. if (!gamepad || !gamepad.isConnected) {
  64130. continue;
  64131. }
  64132. gamepad.update();
  64133. }
  64134. if (this._isMonitoring && !this._scene) {
  64135. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64136. }
  64137. };
  64138. // This function is called only on Chrome, which does not properly support
  64139. // connection/disconnection events and forces you to recopy again the gamepad object
  64140. GamepadManager.prototype._updateGamepadObjects = function () {
  64141. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64142. for (var i = 0; i < gamepads.length; i++) {
  64143. if (gamepads[i]) {
  64144. if (!this._babylonGamepads[gamepads[i].index]) {
  64145. var newGamepad = this._addNewGamepad(gamepads[i]);
  64146. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64147. }
  64148. else {
  64149. // Forced to copy again this object for Chrome for unknown reason
  64150. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64151. if (!this._babylonGamepads[i].isConnected) {
  64152. this._babylonGamepads[i]._isConnected = true;
  64153. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64154. }
  64155. }
  64156. }
  64157. }
  64158. };
  64159. return GamepadManager;
  64160. }());
  64161. BABYLON.GamepadManager = GamepadManager;
  64162. })(BABYLON || (BABYLON = {}));
  64163. //# sourceMappingURL=babylon.gamepadManager.js.map
  64164. var BABYLON;
  64165. (function (BABYLON) {
  64166. var StickValues = /** @class */ (function () {
  64167. function StickValues(x, y) {
  64168. this.x = x;
  64169. this.y = y;
  64170. }
  64171. return StickValues;
  64172. }());
  64173. BABYLON.StickValues = StickValues;
  64174. var Gamepad = /** @class */ (function () {
  64175. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64176. if (leftStickX === void 0) { leftStickX = 0; }
  64177. if (leftStickY === void 0) { leftStickY = 1; }
  64178. if (rightStickX === void 0) { rightStickX = 2; }
  64179. if (rightStickY === void 0) { rightStickY = 3; }
  64180. this.id = id;
  64181. this.index = index;
  64182. this.browserGamepad = browserGamepad;
  64183. this._isConnected = true;
  64184. this._invertLeftStickY = false;
  64185. this.type = Gamepad.GAMEPAD;
  64186. this._leftStickAxisX = leftStickX;
  64187. this._leftStickAxisY = leftStickY;
  64188. this._rightStickAxisX = rightStickX;
  64189. this._rightStickAxisY = rightStickY;
  64190. if (this.browserGamepad.axes.length >= 2) {
  64191. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64192. }
  64193. if (this.browserGamepad.axes.length >= 4) {
  64194. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64195. }
  64196. }
  64197. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64198. get: function () {
  64199. return this._isConnected;
  64200. },
  64201. enumerable: true,
  64202. configurable: true
  64203. });
  64204. Gamepad.prototype.onleftstickchanged = function (callback) {
  64205. this._onleftstickchanged = callback;
  64206. };
  64207. Gamepad.prototype.onrightstickchanged = function (callback) {
  64208. this._onrightstickchanged = callback;
  64209. };
  64210. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64211. get: function () {
  64212. return this._leftStick;
  64213. },
  64214. set: function (newValues) {
  64215. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64216. this._onleftstickchanged(newValues);
  64217. }
  64218. this._leftStick = newValues;
  64219. },
  64220. enumerable: true,
  64221. configurable: true
  64222. });
  64223. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64224. get: function () {
  64225. return this._rightStick;
  64226. },
  64227. set: function (newValues) {
  64228. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64229. this._onrightstickchanged(newValues);
  64230. }
  64231. this._rightStick = newValues;
  64232. },
  64233. enumerable: true,
  64234. configurable: true
  64235. });
  64236. Gamepad.prototype.update = function () {
  64237. if (this._leftStick) {
  64238. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64239. if (this._invertLeftStickY) {
  64240. this.leftStick.y *= -1;
  64241. }
  64242. }
  64243. if (this._rightStick) {
  64244. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64245. }
  64246. };
  64247. Gamepad.prototype.dispose = function () {
  64248. };
  64249. Gamepad.GAMEPAD = 0;
  64250. Gamepad.GENERIC = 1;
  64251. Gamepad.XBOX = 2;
  64252. Gamepad.POSE_ENABLED = 3;
  64253. return Gamepad;
  64254. }());
  64255. BABYLON.Gamepad = Gamepad;
  64256. var GenericPad = /** @class */ (function (_super) {
  64257. __extends(GenericPad, _super);
  64258. function GenericPad(id, index, browserGamepad) {
  64259. var _this = _super.call(this, id, index, browserGamepad) || this;
  64260. _this.onButtonDownObservable = new BABYLON.Observable();
  64261. _this.onButtonUpObservable = new BABYLON.Observable();
  64262. _this.type = Gamepad.GENERIC;
  64263. _this._buttons = new Array(browserGamepad.buttons.length);
  64264. return _this;
  64265. }
  64266. GenericPad.prototype.onbuttondown = function (callback) {
  64267. this._onbuttondown = callback;
  64268. };
  64269. GenericPad.prototype.onbuttonup = function (callback) {
  64270. this._onbuttonup = callback;
  64271. };
  64272. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64273. if (newValue !== currentValue) {
  64274. if (newValue === 1) {
  64275. if (this._onbuttondown) {
  64276. this._onbuttondown(buttonIndex);
  64277. }
  64278. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64279. }
  64280. if (newValue === 0) {
  64281. if (this._onbuttonup) {
  64282. this._onbuttonup(buttonIndex);
  64283. }
  64284. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64285. }
  64286. }
  64287. return newValue;
  64288. };
  64289. GenericPad.prototype.update = function () {
  64290. _super.prototype.update.call(this);
  64291. for (var index = 0; index < this._buttons.length; index++) {
  64292. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64293. }
  64294. };
  64295. GenericPad.prototype.dispose = function () {
  64296. _super.prototype.dispose.call(this);
  64297. this.onButtonDownObservable.clear();
  64298. this.onButtonUpObservable.clear();
  64299. };
  64300. return GenericPad;
  64301. }(Gamepad));
  64302. BABYLON.GenericPad = GenericPad;
  64303. })(BABYLON || (BABYLON = {}));
  64304. //# sourceMappingURL=babylon.gamepad.js.map
  64305. var BABYLON;
  64306. (function (BABYLON) {
  64307. var Xbox360Button;
  64308. (function (Xbox360Button) {
  64309. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64310. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64311. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64312. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64313. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64314. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64315. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64316. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64317. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64318. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64319. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64320. var Xbox360Dpad;
  64321. (function (Xbox360Dpad) {
  64322. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64323. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64324. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64325. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64326. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64327. var Xbox360Pad = /** @class */ (function (_super) {
  64328. __extends(Xbox360Pad, _super);
  64329. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64330. if (xboxOne === void 0) { xboxOne = false; }
  64331. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64332. _this._leftTrigger = 0;
  64333. _this._rightTrigger = 0;
  64334. _this.onButtonDownObservable = new BABYLON.Observable();
  64335. _this.onButtonUpObservable = new BABYLON.Observable();
  64336. _this.onPadDownObservable = new BABYLON.Observable();
  64337. _this.onPadUpObservable = new BABYLON.Observable();
  64338. _this._buttonA = 0;
  64339. _this._buttonB = 0;
  64340. _this._buttonX = 0;
  64341. _this._buttonY = 0;
  64342. _this._buttonBack = 0;
  64343. _this._buttonStart = 0;
  64344. _this._buttonLB = 0;
  64345. _this._buttonRB = 0;
  64346. _this._buttonLeftStick = 0;
  64347. _this._buttonRightStick = 0;
  64348. _this._dPadUp = 0;
  64349. _this._dPadDown = 0;
  64350. _this._dPadLeft = 0;
  64351. _this._dPadRight = 0;
  64352. _this._isXboxOnePad = false;
  64353. _this.type = BABYLON.Gamepad.XBOX;
  64354. _this._isXboxOnePad = xboxOne;
  64355. return _this;
  64356. }
  64357. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64358. this._onlefttriggerchanged = callback;
  64359. };
  64360. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64361. this._onrighttriggerchanged = callback;
  64362. };
  64363. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64364. get: function () {
  64365. return this._leftTrigger;
  64366. },
  64367. set: function (newValue) {
  64368. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64369. this._onlefttriggerchanged(newValue);
  64370. }
  64371. this._leftTrigger = newValue;
  64372. },
  64373. enumerable: true,
  64374. configurable: true
  64375. });
  64376. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64377. get: function () {
  64378. return this._rightTrigger;
  64379. },
  64380. set: function (newValue) {
  64381. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64382. this._onrighttriggerchanged(newValue);
  64383. }
  64384. this._rightTrigger = newValue;
  64385. },
  64386. enumerable: true,
  64387. configurable: true
  64388. });
  64389. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64390. this._onbuttondown = callback;
  64391. };
  64392. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64393. this._onbuttonup = callback;
  64394. };
  64395. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64396. this._ondpaddown = callback;
  64397. };
  64398. Xbox360Pad.prototype.ondpadup = function (callback) {
  64399. this._ondpadup = callback;
  64400. };
  64401. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64402. if (newValue !== currentValue) {
  64403. if (newValue === 1) {
  64404. if (this._onbuttondown) {
  64405. this._onbuttondown(buttonType);
  64406. }
  64407. this.onButtonDownObservable.notifyObservers(buttonType);
  64408. }
  64409. if (newValue === 0) {
  64410. if (this._onbuttonup) {
  64411. this._onbuttonup(buttonType);
  64412. }
  64413. this.onButtonUpObservable.notifyObservers(buttonType);
  64414. }
  64415. }
  64416. return newValue;
  64417. };
  64418. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64419. if (newValue !== currentValue) {
  64420. if (newValue === 1) {
  64421. if (this._ondpaddown) {
  64422. this._ondpaddown(buttonType);
  64423. }
  64424. this.onPadDownObservable.notifyObservers(buttonType);
  64425. }
  64426. if (newValue === 0) {
  64427. if (this._ondpadup) {
  64428. this._ondpadup(buttonType);
  64429. }
  64430. this.onPadUpObservable.notifyObservers(buttonType);
  64431. }
  64432. }
  64433. return newValue;
  64434. };
  64435. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64436. get: function () {
  64437. return this._buttonA;
  64438. },
  64439. set: function (value) {
  64440. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64441. },
  64442. enumerable: true,
  64443. configurable: true
  64444. });
  64445. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64446. get: function () {
  64447. return this._buttonB;
  64448. },
  64449. set: function (value) {
  64450. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64451. },
  64452. enumerable: true,
  64453. configurable: true
  64454. });
  64455. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64456. get: function () {
  64457. return this._buttonX;
  64458. },
  64459. set: function (value) {
  64460. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64461. },
  64462. enumerable: true,
  64463. configurable: true
  64464. });
  64465. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64466. get: function () {
  64467. return this._buttonY;
  64468. },
  64469. set: function (value) {
  64470. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64471. },
  64472. enumerable: true,
  64473. configurable: true
  64474. });
  64475. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64476. get: function () {
  64477. return this._buttonStart;
  64478. },
  64479. set: function (value) {
  64480. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64481. },
  64482. enumerable: true,
  64483. configurable: true
  64484. });
  64485. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64486. get: function () {
  64487. return this._buttonBack;
  64488. },
  64489. set: function (value) {
  64490. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64491. },
  64492. enumerable: true,
  64493. configurable: true
  64494. });
  64495. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64496. get: function () {
  64497. return this._buttonLB;
  64498. },
  64499. set: function (value) {
  64500. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64501. },
  64502. enumerable: true,
  64503. configurable: true
  64504. });
  64505. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64506. get: function () {
  64507. return this._buttonRB;
  64508. },
  64509. set: function (value) {
  64510. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64511. },
  64512. enumerable: true,
  64513. configurable: true
  64514. });
  64515. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64516. get: function () {
  64517. return this._buttonLeftStick;
  64518. },
  64519. set: function (value) {
  64520. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64521. },
  64522. enumerable: true,
  64523. configurable: true
  64524. });
  64525. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64526. get: function () {
  64527. return this._buttonRightStick;
  64528. },
  64529. set: function (value) {
  64530. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64531. },
  64532. enumerable: true,
  64533. configurable: true
  64534. });
  64535. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64536. get: function () {
  64537. return this._dPadUp;
  64538. },
  64539. set: function (value) {
  64540. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64541. },
  64542. enumerable: true,
  64543. configurable: true
  64544. });
  64545. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64546. get: function () {
  64547. return this._dPadDown;
  64548. },
  64549. set: function (value) {
  64550. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64551. },
  64552. enumerable: true,
  64553. configurable: true
  64554. });
  64555. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64556. get: function () {
  64557. return this._dPadLeft;
  64558. },
  64559. set: function (value) {
  64560. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64561. },
  64562. enumerable: true,
  64563. configurable: true
  64564. });
  64565. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64566. get: function () {
  64567. return this._dPadRight;
  64568. },
  64569. set: function (value) {
  64570. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64571. },
  64572. enumerable: true,
  64573. configurable: true
  64574. });
  64575. Xbox360Pad.prototype.update = function () {
  64576. _super.prototype.update.call(this);
  64577. if (this._isXboxOnePad) {
  64578. this.buttonA = this.browserGamepad.buttons[0].value;
  64579. this.buttonB = this.browserGamepad.buttons[1].value;
  64580. this.buttonX = this.browserGamepad.buttons[2].value;
  64581. this.buttonY = this.browserGamepad.buttons[3].value;
  64582. this.buttonLB = this.browserGamepad.buttons[4].value;
  64583. this.buttonRB = this.browserGamepad.buttons[5].value;
  64584. this.leftTrigger = this.browserGamepad.axes[2];
  64585. this.rightTrigger = this.browserGamepad.axes[5];
  64586. this.buttonBack = this.browserGamepad.buttons[9].value;
  64587. this.buttonStart = this.browserGamepad.buttons[8].value;
  64588. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64589. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64590. this.dPadUp = this.browserGamepad.buttons[11].value;
  64591. this.dPadDown = this.browserGamepad.buttons[12].value;
  64592. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64593. this.dPadRight = this.browserGamepad.buttons[14].value;
  64594. }
  64595. else {
  64596. this.buttonA = this.browserGamepad.buttons[0].value;
  64597. this.buttonB = this.browserGamepad.buttons[1].value;
  64598. this.buttonX = this.browserGamepad.buttons[2].value;
  64599. this.buttonY = this.browserGamepad.buttons[3].value;
  64600. this.buttonLB = this.browserGamepad.buttons[4].value;
  64601. this.buttonRB = this.browserGamepad.buttons[5].value;
  64602. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64603. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64604. this.buttonBack = this.browserGamepad.buttons[8].value;
  64605. this.buttonStart = this.browserGamepad.buttons[9].value;
  64606. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64607. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64608. this.dPadUp = this.browserGamepad.buttons[12].value;
  64609. this.dPadDown = this.browserGamepad.buttons[13].value;
  64610. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64611. this.dPadRight = this.browserGamepad.buttons[15].value;
  64612. }
  64613. };
  64614. Xbox360Pad.prototype.dispose = function () {
  64615. _super.prototype.dispose.call(this);
  64616. this.onButtonDownObservable.clear();
  64617. this.onButtonUpObservable.clear();
  64618. this.onPadDownObservable.clear();
  64619. this.onPadUpObservable.clear();
  64620. };
  64621. return Xbox360Pad;
  64622. }(BABYLON.Gamepad));
  64623. BABYLON.Xbox360Pad = Xbox360Pad;
  64624. })(BABYLON || (BABYLON = {}));
  64625. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64626. var BABYLON;
  64627. (function (BABYLON) {
  64628. var PoseEnabledControllerType;
  64629. (function (PoseEnabledControllerType) {
  64630. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64631. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64632. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64633. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64634. /**
  64635. * Google Daydream
  64636. */
  64637. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64638. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64639. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64640. var PoseEnabledControllerHelper = /** @class */ (function () {
  64641. function PoseEnabledControllerHelper() {
  64642. }
  64643. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64644. // Oculus Touch
  64645. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64646. return new BABYLON.OculusTouchController(vrGamepad);
  64647. }
  64648. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64649. return new BABYLON.WindowsMotionController(vrGamepad);
  64650. }
  64651. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64652. return new BABYLON.ViveController(vrGamepad);
  64653. }
  64654. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64655. return new BABYLON.GearVRController(vrGamepad);
  64656. }
  64657. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64658. return new BABYLON.DaydreamController(vrGamepad);
  64659. }
  64660. else {
  64661. return new BABYLON.GenericController(vrGamepad);
  64662. }
  64663. };
  64664. return PoseEnabledControllerHelper;
  64665. }());
  64666. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64667. var PoseEnabledController = /** @class */ (function (_super) {
  64668. __extends(PoseEnabledController, _super);
  64669. function PoseEnabledController(browserGamepad) {
  64670. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64671. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64672. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64673. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64674. // Represents device position and rotation in babylon space
  64675. _this.devicePosition = BABYLON.Vector3.Zero();
  64676. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64677. _this.deviceScaleFactor = 1;
  64678. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64679. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64680. /**
  64681. * Node to be used when casting a ray from the controller
  64682. */
  64683. _this._pointingPoseNode = null;
  64684. _this._workingMatrix = BABYLON.Matrix.Identity();
  64685. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64686. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64687. _this.position = BABYLON.Vector3.Zero();
  64688. _this.rotationQuaternion = new BABYLON.Quaternion();
  64689. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64690. _this._calculatedRotation = new BABYLON.Quaternion();
  64691. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64692. return _this;
  64693. }
  64694. PoseEnabledController.prototype.update = function () {
  64695. _super.prototype.update.call(this);
  64696. var pose = this.browserGamepad.pose;
  64697. this.updateFromDevice(pose);
  64698. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64699. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64700. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64701. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64702. if (this._mesh) {
  64703. this._mesh.position.copyFrom(this.devicePosition);
  64704. if (this._mesh.rotationQuaternion) {
  64705. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64706. }
  64707. }
  64708. };
  64709. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64710. if (poseData) {
  64711. this.rawPose = poseData;
  64712. if (poseData.position) {
  64713. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64714. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64715. this._deviceRoomPosition.z *= -1;
  64716. }
  64717. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64718. this._calculatedPosition.addInPlace(this.position);
  64719. }
  64720. var pose = this.rawPose;
  64721. if (poseData.orientation && pose.orientation) {
  64722. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64723. if (this._mesh) {
  64724. if (this._mesh.getScene().useRightHandedSystem) {
  64725. this._deviceRoomRotationQuaternion.z *= -1;
  64726. this._deviceRoomRotationQuaternion.w *= -1;
  64727. }
  64728. else {
  64729. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64730. }
  64731. }
  64732. // if the camera is set, rotate to the camera's rotation
  64733. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64734. }
  64735. }
  64736. };
  64737. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64738. if (this._mesh) {
  64739. this._mesh.parent = null;
  64740. }
  64741. this._mesh = mesh;
  64742. if (this._poseControlledCamera) {
  64743. this._mesh.parent = this._poseControlledCamera;
  64744. }
  64745. if (!this._mesh.rotationQuaternion) {
  64746. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64747. }
  64748. };
  64749. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64750. this._poseControlledCamera = camera;
  64751. if (this._mesh) {
  64752. this._mesh.parent = this._poseControlledCamera;
  64753. }
  64754. };
  64755. PoseEnabledController.prototype.dispose = function () {
  64756. if (this._mesh) {
  64757. this._mesh.dispose();
  64758. }
  64759. this._mesh = null;
  64760. _super.prototype.dispose.call(this);
  64761. };
  64762. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64763. get: function () {
  64764. return this._mesh;
  64765. },
  64766. enumerable: true,
  64767. configurable: true
  64768. });
  64769. PoseEnabledController.prototype.getForwardRay = function (length) {
  64770. if (length === void 0) { length = 100; }
  64771. if (!this.mesh) {
  64772. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64773. }
  64774. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  64775. var origin = m.getTranslation();
  64776. var forward = new BABYLON.Vector3(0, 0, -1);
  64777. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64778. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64779. return new BABYLON.Ray(origin, direction, length);
  64780. };
  64781. /**
  64782. * Name of the child mesh that can be used to cast a ray from the controller
  64783. */
  64784. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  64785. return PoseEnabledController;
  64786. }(BABYLON.Gamepad));
  64787. BABYLON.PoseEnabledController = PoseEnabledController;
  64788. })(BABYLON || (BABYLON = {}));
  64789. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64790. var BABYLON;
  64791. (function (BABYLON) {
  64792. var WebVRController = /** @class */ (function (_super) {
  64793. __extends(WebVRController, _super);
  64794. function WebVRController(vrGamepad) {
  64795. var _this = _super.call(this, vrGamepad) || this;
  64796. // Observables
  64797. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64798. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64799. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64800. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64801. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64802. _this.pad = { x: 0, y: 0 };
  64803. // avoid GC, store state in a tmp object
  64804. _this._changes = {
  64805. pressChanged: false,
  64806. touchChanged: false,
  64807. valueChanged: false,
  64808. changed: false
  64809. };
  64810. _this._buttons = new Array(vrGamepad.buttons.length);
  64811. _this.hand = vrGamepad.hand;
  64812. return _this;
  64813. }
  64814. WebVRController.prototype.onButtonStateChange = function (callback) {
  64815. this._onButtonStateChange = callback;
  64816. };
  64817. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64818. get: function () {
  64819. return this._defaultModel;
  64820. },
  64821. enumerable: true,
  64822. configurable: true
  64823. });
  64824. WebVRController.prototype.update = function () {
  64825. _super.prototype.update.call(this);
  64826. for (var index = 0; index < this._buttons.length; index++) {
  64827. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64828. }
  64829. ;
  64830. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64831. this.pad.x = this.leftStick.x;
  64832. this.pad.y = this.leftStick.y;
  64833. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64834. }
  64835. };
  64836. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64837. if (!newState) {
  64838. newState = {
  64839. pressed: false,
  64840. touched: false,
  64841. value: 0
  64842. };
  64843. }
  64844. if (!currentState) {
  64845. this._buttons[buttonIndex] = {
  64846. pressed: newState.pressed,
  64847. touched: newState.touched,
  64848. value: newState.value
  64849. };
  64850. return;
  64851. }
  64852. this._checkChanges(newState, currentState);
  64853. if (this._changes.changed) {
  64854. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64855. this._handleButtonChange(buttonIndex, newState, this._changes);
  64856. }
  64857. this._buttons[buttonIndex].pressed = newState.pressed;
  64858. this._buttons[buttonIndex].touched = newState.touched;
  64859. // oculus triggers are never 0, thou not touched.
  64860. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64861. };
  64862. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64863. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64864. this._changes.touchChanged = newState.touched !== currentState.touched;
  64865. this._changes.valueChanged = newState.value !== currentState.value;
  64866. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64867. return this._changes;
  64868. };
  64869. WebVRController.prototype.dispose = function () {
  64870. _super.prototype.dispose.call(this);
  64871. this.onTriggerStateChangedObservable.clear();
  64872. this.onMainButtonStateChangedObservable.clear();
  64873. this.onSecondaryButtonStateChangedObservable.clear();
  64874. this.onPadStateChangedObservable.clear();
  64875. this.onPadValuesChangedObservable.clear();
  64876. };
  64877. return WebVRController;
  64878. }(BABYLON.PoseEnabledController));
  64879. BABYLON.WebVRController = WebVRController;
  64880. })(BABYLON || (BABYLON = {}));
  64881. //# sourceMappingURL=babylon.webVRController.js.map
  64882. var BABYLON;
  64883. (function (BABYLON) {
  64884. var OculusTouchController = /** @class */ (function (_super) {
  64885. __extends(OculusTouchController, _super);
  64886. function OculusTouchController(vrGamepad) {
  64887. var _this = _super.call(this, vrGamepad) || this;
  64888. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64889. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64890. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64891. return _this;
  64892. }
  64893. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64894. var _this = this;
  64895. var meshName;
  64896. // Hand
  64897. if (this.hand === 'left') {
  64898. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64899. }
  64900. else {
  64901. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64902. }
  64903. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64904. /*
  64905. Parent Mesh name: oculus_touch_left
  64906. - body
  64907. - trigger
  64908. - thumbstick
  64909. - grip
  64910. - button_y
  64911. - button_x
  64912. - button_enter
  64913. */
  64914. _this._defaultModel = newMeshes[1];
  64915. _this.attachToMesh(_this._defaultModel);
  64916. if (meshLoaded) {
  64917. meshLoaded(_this._defaultModel);
  64918. }
  64919. });
  64920. };
  64921. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64922. // helper getters for left and right hand.
  64923. get: function () {
  64924. if (this.hand === 'right') {
  64925. return this.onMainButtonStateChangedObservable;
  64926. }
  64927. else {
  64928. throw new Error('No A button on left hand');
  64929. }
  64930. },
  64931. enumerable: true,
  64932. configurable: true
  64933. });
  64934. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64935. get: function () {
  64936. if (this.hand === 'right') {
  64937. return this.onSecondaryButtonStateChangedObservable;
  64938. }
  64939. else {
  64940. throw new Error('No B button on left hand');
  64941. }
  64942. },
  64943. enumerable: true,
  64944. configurable: true
  64945. });
  64946. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64947. get: function () {
  64948. if (this.hand === 'left') {
  64949. return this.onMainButtonStateChangedObservable;
  64950. }
  64951. else {
  64952. throw new Error('No X button on right hand');
  64953. }
  64954. },
  64955. enumerable: true,
  64956. configurable: true
  64957. });
  64958. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64959. get: function () {
  64960. if (this.hand === 'left') {
  64961. return this.onSecondaryButtonStateChangedObservable;
  64962. }
  64963. else {
  64964. throw new Error('No Y button on right hand');
  64965. }
  64966. },
  64967. enumerable: true,
  64968. configurable: true
  64969. });
  64970. /*
  64971. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64972. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64973. 2) secondary trigger (same)
  64974. 3) A (right) X (left), touch, pressed = value
  64975. 4) B / Y
  64976. 5) thumb rest
  64977. */
  64978. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64979. var notifyObject = state; //{ state: state, changes: changes };
  64980. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64981. switch (buttonIdx) {
  64982. case 0:
  64983. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64984. return;
  64985. case 1:// index trigger
  64986. if (this._defaultModel) {
  64987. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64988. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64989. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64990. }
  64991. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64992. return;
  64993. case 2:// secondary trigger
  64994. if (this._defaultModel) {
  64995. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64996. }
  64997. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64998. return;
  64999. case 3:
  65000. if (this._defaultModel) {
  65001. if (notifyObject.pressed) {
  65002. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65003. }
  65004. else {
  65005. (this._defaultModel.getChildren()[1]).position.y = 0;
  65006. }
  65007. }
  65008. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65009. return;
  65010. case 4:
  65011. if (this._defaultModel) {
  65012. if (notifyObject.pressed) {
  65013. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65014. }
  65015. else {
  65016. (this._defaultModel.getChildren()[2]).position.y = 0;
  65017. }
  65018. }
  65019. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65020. return;
  65021. case 5:
  65022. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65023. return;
  65024. }
  65025. };
  65026. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65027. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65028. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65029. return OculusTouchController;
  65030. }(BABYLON.WebVRController));
  65031. BABYLON.OculusTouchController = OculusTouchController;
  65032. })(BABYLON || (BABYLON = {}));
  65033. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65034. var BABYLON;
  65035. (function (BABYLON) {
  65036. var ViveController = /** @class */ (function (_super) {
  65037. __extends(ViveController, _super);
  65038. function ViveController(vrGamepad) {
  65039. var _this = _super.call(this, vrGamepad) || this;
  65040. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65041. _this._invertLeftStickY = true;
  65042. return _this;
  65043. }
  65044. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65045. var _this = this;
  65046. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65047. /*
  65048. Parent Mesh name: ViveWand
  65049. - body
  65050. - r_gripper
  65051. - l_gripper
  65052. - menu_button
  65053. - system_button
  65054. - trackpad
  65055. - trigger
  65056. - LED
  65057. */
  65058. _this._defaultModel = newMeshes[1];
  65059. _this.attachToMesh(_this._defaultModel);
  65060. if (meshLoaded) {
  65061. meshLoaded(_this._defaultModel);
  65062. }
  65063. });
  65064. };
  65065. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65066. get: function () {
  65067. return this.onMainButtonStateChangedObservable;
  65068. },
  65069. enumerable: true,
  65070. configurable: true
  65071. });
  65072. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65073. get: function () {
  65074. return this.onMainButtonStateChangedObservable;
  65075. },
  65076. enumerable: true,
  65077. configurable: true
  65078. });
  65079. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65080. get: function () {
  65081. return this.onSecondaryButtonStateChangedObservable;
  65082. },
  65083. enumerable: true,
  65084. configurable: true
  65085. });
  65086. /**
  65087. * Vive mapping:
  65088. * 0: touchpad
  65089. * 1: trigger
  65090. * 2: left AND right buttons
  65091. * 3: menu button
  65092. */
  65093. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65094. var notifyObject = state; //{ state: state, changes: changes };
  65095. switch (buttonIdx) {
  65096. case 0:
  65097. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65098. return;
  65099. case 1:// index trigger
  65100. if (this._defaultModel) {
  65101. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65102. }
  65103. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65104. return;
  65105. case 2:// left AND right button
  65106. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65107. return;
  65108. case 3:
  65109. if (this._defaultModel) {
  65110. if (notifyObject.pressed) {
  65111. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65112. }
  65113. else {
  65114. (this._defaultModel.getChildren()[2]).position.y = 0;
  65115. }
  65116. }
  65117. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65118. return;
  65119. }
  65120. };
  65121. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65122. ViveController.MODEL_FILENAME = 'wand.babylon';
  65123. return ViveController;
  65124. }(BABYLON.WebVRController));
  65125. BABYLON.ViveController = ViveController;
  65126. })(BABYLON || (BABYLON = {}));
  65127. //# sourceMappingURL=babylon.viveController.js.map
  65128. var BABYLON;
  65129. (function (BABYLON) {
  65130. var GenericController = /** @class */ (function (_super) {
  65131. __extends(GenericController, _super);
  65132. function GenericController(vrGamepad) {
  65133. return _super.call(this, vrGamepad) || this;
  65134. }
  65135. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65136. var _this = this;
  65137. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65138. _this._defaultModel = newMeshes[1];
  65139. _this.attachToMesh(_this._defaultModel);
  65140. if (meshLoaded) {
  65141. meshLoaded(_this._defaultModel);
  65142. }
  65143. });
  65144. };
  65145. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65146. console.log("Button id: " + buttonIdx + "state: ");
  65147. console.dir(state);
  65148. };
  65149. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65150. GenericController.MODEL_FILENAME = 'generic.babylon';
  65151. return GenericController;
  65152. }(BABYLON.WebVRController));
  65153. BABYLON.GenericController = GenericController;
  65154. })(BABYLON || (BABYLON = {}));
  65155. //# sourceMappingURL=babylon.genericController.js.map
  65156. var BABYLON;
  65157. (function (BABYLON) {
  65158. var LoadedMeshInfo = /** @class */ (function () {
  65159. function LoadedMeshInfo() {
  65160. this.buttonMeshes = {};
  65161. this.axisMeshes = {};
  65162. }
  65163. return LoadedMeshInfo;
  65164. }());
  65165. var WindowsMotionController = /** @class */ (function (_super) {
  65166. __extends(WindowsMotionController, _super);
  65167. function WindowsMotionController(vrGamepad) {
  65168. var _this = _super.call(this, vrGamepad) || this;
  65169. _this._mapping = {
  65170. // Semantic button names
  65171. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65172. // A mapping of the button name to glTF model node name
  65173. // that should be transformed by button value.
  65174. buttonMeshNames: {
  65175. 'trigger': 'SELECT',
  65176. 'menu': 'MENU',
  65177. 'grip': 'GRASP',
  65178. 'thumbstick': 'THUMBSTICK_PRESS',
  65179. 'trackpad': 'TOUCHPAD_PRESS'
  65180. },
  65181. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65182. buttonObservableNames: {
  65183. 'trigger': 'onTriggerStateChangedObservable',
  65184. 'menu': 'onSecondaryButtonStateChangedObservable',
  65185. 'grip': 'onMainButtonStateChangedObservable',
  65186. 'thumbstick': 'onPadStateChangedObservable',
  65187. 'trackpad': 'onTrackpadChangedObservable'
  65188. },
  65189. // A mapping of the axis name to glTF model node name
  65190. // that should be transformed by axis value.
  65191. // This array mirrors the browserGamepad.axes array, such that
  65192. // the mesh corresponding to axis 0 is in this array index 0.
  65193. axisMeshNames: [
  65194. 'THUMBSTICK_X',
  65195. 'THUMBSTICK_Y',
  65196. 'TOUCHPAD_TOUCH_X',
  65197. 'TOUCHPAD_TOUCH_Y'
  65198. ],
  65199. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65200. };
  65201. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65202. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65203. _this.trackpad = { x: 0, y: 0 };
  65204. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65205. _this._loadedMeshInfo = null;
  65206. return _this;
  65207. }
  65208. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65209. get: function () {
  65210. return this.onTriggerStateChangedObservable;
  65211. },
  65212. enumerable: true,
  65213. configurable: true
  65214. });
  65215. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65216. get: function () {
  65217. return this.onSecondaryButtonStateChangedObservable;
  65218. },
  65219. enumerable: true,
  65220. configurable: true
  65221. });
  65222. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65223. get: function () {
  65224. return this.onMainButtonStateChangedObservable;
  65225. },
  65226. enumerable: true,
  65227. configurable: true
  65228. });
  65229. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65230. get: function () {
  65231. return this.onPadStateChangedObservable;
  65232. },
  65233. enumerable: true,
  65234. configurable: true
  65235. });
  65236. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65237. get: function () {
  65238. return this.onTrackpadChangedObservable;
  65239. },
  65240. enumerable: true,
  65241. configurable: true
  65242. });
  65243. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65244. get: function () {
  65245. return this.onTrackpadValuesChangedObservable;
  65246. },
  65247. enumerable: true,
  65248. configurable: true
  65249. });
  65250. /**
  65251. * Called once per frame by the engine.
  65252. */
  65253. WindowsMotionController.prototype.update = function () {
  65254. _super.prototype.update.call(this);
  65255. if (this.browserGamepad.axes) {
  65256. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65257. this.trackpad.x = this.browserGamepad["axes"][2];
  65258. this.trackpad.y = this.browserGamepad["axes"][3];
  65259. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65260. }
  65261. // Only need to animate axes if there is a loaded mesh
  65262. if (this._loadedMeshInfo) {
  65263. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65264. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65265. }
  65266. }
  65267. }
  65268. };
  65269. /**
  65270. * Called once for each button that changed state since the last frame
  65271. * @param buttonIdx Which button index changed
  65272. * @param state New state of the button
  65273. * @param changes Which properties on the state changed since last frame
  65274. */
  65275. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65276. var buttonName = this._mapping.buttons[buttonIdx];
  65277. if (!buttonName) {
  65278. return;
  65279. }
  65280. // Only emit events for buttons that we know how to map from index to name
  65281. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65282. if (observable) {
  65283. observable.notifyObservers(state);
  65284. }
  65285. this.lerpButtonTransform(buttonName, state.value);
  65286. };
  65287. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65288. // If there is no loaded mesh, there is nothing to transform.
  65289. if (!this._loadedMeshInfo) {
  65290. return;
  65291. }
  65292. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65293. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65294. return;
  65295. }
  65296. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65297. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65298. };
  65299. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65300. if (!this._loadedMeshInfo) {
  65301. return;
  65302. }
  65303. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65304. if (!meshInfo) {
  65305. return;
  65306. }
  65307. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65308. return;
  65309. }
  65310. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65311. var lerpValue = axisValue * 0.5 + 0.5;
  65312. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65313. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65314. };
  65315. /**
  65316. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65317. * @param scene scene in which to add meshes
  65318. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65319. */
  65320. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65321. var _this = this;
  65322. if (forceDefault === void 0) { forceDefault = false; }
  65323. var path;
  65324. var filename;
  65325. // Checking if GLB loader is present
  65326. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65327. // Determine the device specific folder based on the ID suffix
  65328. var device = 'default';
  65329. if (this.id && !forceDefault) {
  65330. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65331. device = ((match && match[0]) || device);
  65332. }
  65333. // Hand
  65334. if (this.hand === 'left') {
  65335. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65336. }
  65337. else {
  65338. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65339. }
  65340. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65341. }
  65342. else {
  65343. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65344. path = BABYLON.GenericController.MODEL_BASE_URL;
  65345. filename = BABYLON.GenericController.MODEL_FILENAME;
  65346. }
  65347. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65348. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65349. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65350. if (!_this._loadedMeshInfo) {
  65351. return;
  65352. }
  65353. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65354. _this.attachToMesh(_this._defaultModel);
  65355. if (meshLoaded) {
  65356. meshLoaded(_this._defaultModel);
  65357. }
  65358. }, null, function (scene, message) {
  65359. BABYLON.Tools.Log(message);
  65360. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65361. if (!forceDefault) {
  65362. _this.initControllerMesh(scene, meshLoaded, true);
  65363. }
  65364. });
  65365. };
  65366. /**
  65367. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65368. * can be transformed by button presses and axes values, based on this._mapping.
  65369. *
  65370. * @param scene scene in which the meshes exist
  65371. * @param meshes list of meshes that make up the controller model to process
  65372. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65373. */
  65374. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65375. var loadedMeshInfo = null;
  65376. // Create a new mesh to contain the glTF hierarchy
  65377. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65378. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65379. var childMesh = null;
  65380. for (var i = 0; i < meshes.length; i++) {
  65381. var mesh = meshes[i];
  65382. if (!mesh.parent) {
  65383. // Exclude controller meshes from picking results
  65384. mesh.isPickable = false;
  65385. // Handle root node, attach to the new parentMesh
  65386. childMesh = mesh;
  65387. break;
  65388. }
  65389. }
  65390. if (childMesh) {
  65391. childMesh.setParent(parentMesh);
  65392. // Create our mesh info. Note that this method will always return non-null.
  65393. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65394. }
  65395. else {
  65396. BABYLON.Tools.Warn('Could not find root node in model file.');
  65397. }
  65398. return loadedMeshInfo;
  65399. };
  65400. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65401. var loadedMeshInfo = new LoadedMeshInfo();
  65402. var i;
  65403. loadedMeshInfo.rootNode = rootNode;
  65404. // Reset the caches
  65405. loadedMeshInfo.buttonMeshes = {};
  65406. loadedMeshInfo.axisMeshes = {};
  65407. // Button Meshes
  65408. for (i = 0; i < this._mapping.buttons.length; i++) {
  65409. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65410. if (!buttonMeshName) {
  65411. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65412. continue;
  65413. }
  65414. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65415. if (!buttonMesh) {
  65416. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65417. continue;
  65418. }
  65419. var buttonMeshInfo = {
  65420. index: i,
  65421. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65422. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65423. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65424. };
  65425. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65426. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65427. }
  65428. else {
  65429. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65430. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65431. '(VALUE: ' + !!buttonMeshInfo.value +
  65432. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65433. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65434. ')');
  65435. }
  65436. }
  65437. // Axis Meshes
  65438. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65439. var axisMeshName = this._mapping.axisMeshNames[i];
  65440. if (!axisMeshName) {
  65441. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65442. continue;
  65443. }
  65444. var axisMesh = getChildByName(rootNode, axisMeshName);
  65445. if (!axisMesh) {
  65446. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65447. continue;
  65448. }
  65449. var axisMeshInfo = {
  65450. index: i,
  65451. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65452. min: getImmediateChildByName(axisMesh, 'MIN'),
  65453. max: getImmediateChildByName(axisMesh, 'MAX')
  65454. };
  65455. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65456. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65457. }
  65458. else {
  65459. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65460. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65461. '(VALUE: ' + !!axisMeshInfo.value +
  65462. ', MIN: ' + !!axisMeshInfo.min +
  65463. ', MAX:' + !!axisMeshInfo.max +
  65464. ')');
  65465. }
  65466. }
  65467. // Pointing Ray
  65468. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65469. if (!loadedMeshInfo.pointingPoseNode) {
  65470. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65471. }
  65472. return loadedMeshInfo;
  65473. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65474. function getChildByName(node, name) {
  65475. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65476. }
  65477. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65478. function getImmediateChildByName(node, name) {
  65479. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65480. }
  65481. };
  65482. WindowsMotionController.prototype.getForwardRay = function (length) {
  65483. if (length === void 0) { length = 100; }
  65484. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65485. return _super.prototype.getForwardRay.call(this, length);
  65486. }
  65487. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65488. var origin = m.getTranslation();
  65489. var forward = new BABYLON.Vector3(0, 0, -1);
  65490. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65491. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65492. return new BABYLON.Ray(origin, direction, length);
  65493. };
  65494. WindowsMotionController.prototype.dispose = function () {
  65495. _super.prototype.dispose.call(this);
  65496. this.onTrackpadChangedObservable.clear();
  65497. };
  65498. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65499. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65500. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65501. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65502. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65503. return WindowsMotionController;
  65504. }(BABYLON.WebVRController));
  65505. BABYLON.WindowsMotionController = WindowsMotionController;
  65506. })(BABYLON || (BABYLON = {}));
  65507. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65508. var BABYLON;
  65509. (function (BABYLON) {
  65510. var GearVRController = /** @class */ (function (_super) {
  65511. __extends(GearVRController, _super);
  65512. function GearVRController(vrGamepad) {
  65513. var _this = _super.call(this, vrGamepad) || this;
  65514. _this._buttonIndexToObservableNameMap = [
  65515. 'onTrackpadChangedObservable',
  65516. 'onTriggerStateChangedObservable' // Trigger
  65517. ];
  65518. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65519. return _this;
  65520. }
  65521. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65522. var _this = this;
  65523. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65524. _this._defaultModel = newMeshes[1];
  65525. _this.attachToMesh(_this._defaultModel);
  65526. if (meshLoaded) {
  65527. meshLoaded(_this._defaultModel);
  65528. }
  65529. });
  65530. };
  65531. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65532. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65533. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65534. // Only emit events for buttons that we know how to map from index to observable
  65535. var observable = this[observableName];
  65536. if (observable) {
  65537. observable.notifyObservers(state);
  65538. }
  65539. }
  65540. };
  65541. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65542. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65543. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65544. return GearVRController;
  65545. }(BABYLON.WebVRController));
  65546. BABYLON.GearVRController = GearVRController;
  65547. })(BABYLON || (BABYLON = {}));
  65548. //# sourceMappingURL=babylon.gearVRController.js.map
  65549. var BABYLON;
  65550. (function (BABYLON) {
  65551. /**
  65552. * Google Daydream controller
  65553. */
  65554. var DaydreamController = /** @class */ (function (_super) {
  65555. __extends(DaydreamController, _super);
  65556. function DaydreamController(vrGamepad) {
  65557. var _this = _super.call(this, vrGamepad) || this;
  65558. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65559. return _this;
  65560. }
  65561. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65562. var _this = this;
  65563. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65564. _this._defaultModel = newMeshes[1];
  65565. _this.attachToMesh(_this._defaultModel);
  65566. if (meshLoaded) {
  65567. meshLoaded(_this._defaultModel);
  65568. }
  65569. });
  65570. };
  65571. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65572. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65573. if (buttonIdx === 0) {
  65574. var observable = this.onTriggerStateChangedObservable;
  65575. if (observable) {
  65576. observable.notifyObservers(state);
  65577. }
  65578. }
  65579. else {
  65580. // If the app or home buttons are ever made available
  65581. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65582. }
  65583. };
  65584. /**
  65585. * Base Url for the controller model.
  65586. */
  65587. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65588. /**
  65589. * File name for the controller model.
  65590. */
  65591. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65592. /**
  65593. * Gamepad Id prefix used to identify Daydream Controller.
  65594. */
  65595. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65596. return DaydreamController;
  65597. }(BABYLON.WebVRController));
  65598. BABYLON.DaydreamController = DaydreamController;
  65599. })(BABYLON || (BABYLON = {}));
  65600. //# sourceMappingURL=babylon.daydreamController.js.map
  65601. var BABYLON;
  65602. (function (BABYLON) {
  65603. var FollowCamera = /** @class */ (function (_super) {
  65604. __extends(FollowCamera, _super);
  65605. function FollowCamera(name, position, scene, lockedTarget) {
  65606. if (lockedTarget === void 0) { lockedTarget = null; }
  65607. var _this = _super.call(this, name, position, scene) || this;
  65608. _this.radius = 12;
  65609. _this.rotationOffset = 0;
  65610. _this.heightOffset = 4;
  65611. _this.cameraAcceleration = 0.05;
  65612. _this.maxCameraSpeed = 20;
  65613. _this.lockedTarget = lockedTarget;
  65614. return _this;
  65615. }
  65616. FollowCamera.prototype.getRadians = function (degrees) {
  65617. return degrees * Math.PI / 180;
  65618. };
  65619. FollowCamera.prototype.follow = function (cameraTarget) {
  65620. if (!cameraTarget)
  65621. return;
  65622. var yRotation;
  65623. if (cameraTarget.rotationQuaternion) {
  65624. var rotMatrix = new BABYLON.Matrix();
  65625. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65626. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65627. }
  65628. else {
  65629. yRotation = cameraTarget.rotation.y;
  65630. }
  65631. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65632. var targetPosition = cameraTarget.getAbsolutePosition();
  65633. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65634. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65635. var dx = targetX - this.position.x;
  65636. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65637. var dz = (targetZ) - this.position.z;
  65638. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65639. var vy = dy * this.cameraAcceleration;
  65640. var vz = dz * this.cameraAcceleration * 2;
  65641. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65642. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65643. }
  65644. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65645. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65646. }
  65647. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65648. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65649. }
  65650. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65651. this.setTarget(targetPosition);
  65652. };
  65653. FollowCamera.prototype._checkInputs = function () {
  65654. _super.prototype._checkInputs.call(this);
  65655. if (this.lockedTarget) {
  65656. this.follow(this.lockedTarget);
  65657. }
  65658. };
  65659. FollowCamera.prototype.getClassName = function () {
  65660. return "FollowCamera";
  65661. };
  65662. __decorate([
  65663. BABYLON.serialize()
  65664. ], FollowCamera.prototype, "radius", void 0);
  65665. __decorate([
  65666. BABYLON.serialize()
  65667. ], FollowCamera.prototype, "rotationOffset", void 0);
  65668. __decorate([
  65669. BABYLON.serialize()
  65670. ], FollowCamera.prototype, "heightOffset", void 0);
  65671. __decorate([
  65672. BABYLON.serialize()
  65673. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65674. __decorate([
  65675. BABYLON.serialize()
  65676. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65677. __decorate([
  65678. BABYLON.serializeAsMeshReference("lockedTargetId")
  65679. ], FollowCamera.prototype, "lockedTarget", void 0);
  65680. return FollowCamera;
  65681. }(BABYLON.TargetCamera));
  65682. BABYLON.FollowCamera = FollowCamera;
  65683. var ArcFollowCamera = /** @class */ (function (_super) {
  65684. __extends(ArcFollowCamera, _super);
  65685. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65686. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65687. _this.alpha = alpha;
  65688. _this.beta = beta;
  65689. _this.radius = radius;
  65690. _this.target = target;
  65691. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65692. _this.follow();
  65693. return _this;
  65694. }
  65695. ArcFollowCamera.prototype.follow = function () {
  65696. if (!this.target) {
  65697. return;
  65698. }
  65699. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65700. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65701. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65702. var targetPosition = this.target.getAbsolutePosition();
  65703. this.position = targetPosition.add(this._cartesianCoordinates);
  65704. this.setTarget(targetPosition);
  65705. };
  65706. ArcFollowCamera.prototype._checkInputs = function () {
  65707. _super.prototype._checkInputs.call(this);
  65708. this.follow();
  65709. };
  65710. ArcFollowCamera.prototype.getClassName = function () {
  65711. return "ArcFollowCamera";
  65712. };
  65713. return ArcFollowCamera;
  65714. }(BABYLON.TargetCamera));
  65715. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65716. })(BABYLON || (BABYLON = {}));
  65717. //# sourceMappingURL=babylon.followCamera.js.map
  65718. var BABYLON;
  65719. (function (BABYLON) {
  65720. // We're mainly based on the logic defined into the FreeCamera code
  65721. var UniversalCamera = /** @class */ (function (_super) {
  65722. __extends(UniversalCamera, _super);
  65723. //-- end properties for backward compatibility for inputs
  65724. function UniversalCamera(name, position, scene) {
  65725. var _this = _super.call(this, name, position, scene) || this;
  65726. _this.inputs.addGamepad();
  65727. return _this;
  65728. }
  65729. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65730. //-- Begin properties for backward compatibility for inputs
  65731. get: function () {
  65732. var gamepad = this.inputs.attached["gamepad"];
  65733. if (gamepad)
  65734. return gamepad.gamepadAngularSensibility;
  65735. return 0;
  65736. },
  65737. set: function (value) {
  65738. var gamepad = this.inputs.attached["gamepad"];
  65739. if (gamepad)
  65740. gamepad.gamepadAngularSensibility = value;
  65741. },
  65742. enumerable: true,
  65743. configurable: true
  65744. });
  65745. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65746. get: function () {
  65747. var gamepad = this.inputs.attached["gamepad"];
  65748. if (gamepad)
  65749. return gamepad.gamepadMoveSensibility;
  65750. return 0;
  65751. },
  65752. set: function (value) {
  65753. var gamepad = this.inputs.attached["gamepad"];
  65754. if (gamepad)
  65755. gamepad.gamepadMoveSensibility = value;
  65756. },
  65757. enumerable: true,
  65758. configurable: true
  65759. });
  65760. UniversalCamera.prototype.getClassName = function () {
  65761. return "UniversalCamera";
  65762. };
  65763. return UniversalCamera;
  65764. }(BABYLON.TouchCamera));
  65765. BABYLON.UniversalCamera = UniversalCamera;
  65766. })(BABYLON || (BABYLON = {}));
  65767. //# sourceMappingURL=babylon.universalCamera.js.map
  65768. var BABYLON;
  65769. (function (BABYLON) {
  65770. // We're mainly based on the logic defined into the FreeCamera code
  65771. var GamepadCamera = /** @class */ (function (_super) {
  65772. __extends(GamepadCamera, _super);
  65773. //-- end properties for backward compatibility for inputs
  65774. function GamepadCamera(name, position, scene) {
  65775. return _super.call(this, name, position, scene) || this;
  65776. }
  65777. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65778. //-- Begin properties for backward compatibility for inputs
  65779. get: function () {
  65780. var gamepad = this.inputs.attached["gamepad"];
  65781. if (gamepad)
  65782. return gamepad.gamepadAngularSensibility;
  65783. return 0;
  65784. },
  65785. set: function (value) {
  65786. var gamepad = this.inputs.attached["gamepad"];
  65787. if (gamepad)
  65788. gamepad.gamepadAngularSensibility = value;
  65789. },
  65790. enumerable: true,
  65791. configurable: true
  65792. });
  65793. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65794. get: function () {
  65795. var gamepad = this.inputs.attached["gamepad"];
  65796. if (gamepad)
  65797. return gamepad.gamepadMoveSensibility;
  65798. return 0;
  65799. },
  65800. set: function (value) {
  65801. var gamepad = this.inputs.attached["gamepad"];
  65802. if (gamepad)
  65803. gamepad.gamepadMoveSensibility = value;
  65804. },
  65805. enumerable: true,
  65806. configurable: true
  65807. });
  65808. GamepadCamera.prototype.getClassName = function () {
  65809. return "GamepadCamera";
  65810. };
  65811. return GamepadCamera;
  65812. }(BABYLON.UniversalCamera));
  65813. BABYLON.GamepadCamera = GamepadCamera;
  65814. })(BABYLON || (BABYLON = {}));
  65815. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65816. var BABYLON;
  65817. (function (BABYLON) {
  65818. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65819. function PostProcessRenderPipelineManager() {
  65820. this._renderPipelines = {};
  65821. }
  65822. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65823. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65824. };
  65825. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65826. if (unique === void 0) { unique = false; }
  65827. var renderPipeline = this._renderPipelines[renderPipelineName];
  65828. if (!renderPipeline) {
  65829. return;
  65830. }
  65831. renderPipeline._attachCameras(cameras, unique);
  65832. };
  65833. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65834. var renderPipeline = this._renderPipelines[renderPipelineName];
  65835. if (!renderPipeline) {
  65836. return;
  65837. }
  65838. renderPipeline._detachCameras(cameras);
  65839. };
  65840. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65841. var renderPipeline = this._renderPipelines[renderPipelineName];
  65842. if (!renderPipeline) {
  65843. return;
  65844. }
  65845. renderPipeline._enableEffect(renderEffectName, cameras);
  65846. };
  65847. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65848. var renderPipeline = this._renderPipelines[renderPipelineName];
  65849. if (!renderPipeline) {
  65850. return;
  65851. }
  65852. renderPipeline._disableEffect(renderEffectName, cameras);
  65853. };
  65854. PostProcessRenderPipelineManager.prototype.update = function () {
  65855. for (var renderPipelineName in this._renderPipelines) {
  65856. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65857. var pipeline = this._renderPipelines[renderPipelineName];
  65858. if (!pipeline.isSupported) {
  65859. pipeline.dispose();
  65860. delete this._renderPipelines[renderPipelineName];
  65861. }
  65862. else {
  65863. pipeline._update();
  65864. }
  65865. }
  65866. }
  65867. };
  65868. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65869. for (var renderPipelineName in this._renderPipelines) {
  65870. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65871. var pipeline = this._renderPipelines[renderPipelineName];
  65872. pipeline._rebuild();
  65873. }
  65874. }
  65875. };
  65876. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65877. for (var renderPipelineName in this._renderPipelines) {
  65878. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65879. var pipeline = this._renderPipelines[renderPipelineName];
  65880. pipeline.dispose();
  65881. }
  65882. }
  65883. };
  65884. return PostProcessRenderPipelineManager;
  65885. }());
  65886. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65887. })(BABYLON || (BABYLON = {}));
  65888. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65889. var BABYLON;
  65890. (function (BABYLON) {
  65891. /**
  65892. * This represents a set of one or more post processes in Babylon.
  65893. * A post process can be used to apply a shader to a texture after it is rendered.
  65894. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65895. */
  65896. var PostProcessRenderEffect = /** @class */ (function () {
  65897. /**
  65898. * Instantiates a post process render effect.
  65899. * A post process can be used to apply a shader to a texture after it is rendered.
  65900. * @param engine The engine the effect is tied to
  65901. * @param name The name of the effect
  65902. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65903. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65904. */
  65905. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65906. this._name = name;
  65907. this._singleInstance = singleInstance || true;
  65908. this._getPostProcesses = getPostProcesses;
  65909. this._cameras = {};
  65910. this._indicesForCamera = {};
  65911. this._postProcesses = {};
  65912. }
  65913. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65914. /**
  65915. * Checks if all the post processes in the effect are supported.
  65916. */
  65917. get: function () {
  65918. for (var index in this._postProcesses) {
  65919. for (var ppIndex in this._postProcesses[index]) {
  65920. if (!this._postProcesses[index][ppIndex].isSupported) {
  65921. return false;
  65922. }
  65923. }
  65924. }
  65925. return true;
  65926. },
  65927. enumerable: true,
  65928. configurable: true
  65929. });
  65930. /**
  65931. * Updates the current state of the effect
  65932. */
  65933. PostProcessRenderEffect.prototype._update = function () {
  65934. };
  65935. /**
  65936. * Attaches the effect on cameras
  65937. * @param cameras The camera to attach to.
  65938. */
  65939. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65940. var _this = this;
  65941. var cameraKey;
  65942. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65943. if (!cams) {
  65944. return;
  65945. }
  65946. for (var i = 0; i < cams.length; i++) {
  65947. var camera = cams[i];
  65948. var cameraName = camera.name;
  65949. if (this._singleInstance) {
  65950. cameraKey = 0;
  65951. }
  65952. else {
  65953. cameraKey = cameraName;
  65954. }
  65955. if (!this._postProcesses[cameraKey]) {
  65956. var postProcess = this._getPostProcesses();
  65957. if (postProcess) {
  65958. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65959. }
  65960. }
  65961. if (!this._indicesForCamera[cameraName]) {
  65962. this._indicesForCamera[cameraName] = [];
  65963. }
  65964. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65965. var index = camera.attachPostProcess(postProcess);
  65966. _this._indicesForCamera[cameraName].push(index);
  65967. });
  65968. if (!this._cameras[cameraName]) {
  65969. this._cameras[cameraName] = camera;
  65970. }
  65971. }
  65972. };
  65973. /**
  65974. * Detatches the effect on cameras
  65975. * @param cameras The camera to detatch from.
  65976. */
  65977. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65978. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65979. if (!cams) {
  65980. return;
  65981. }
  65982. for (var i = 0; i < cams.length; i++) {
  65983. var camera = cams[i];
  65984. var cameraName = camera.name;
  65985. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65986. camera.detachPostProcess(postProcess);
  65987. });
  65988. if (this._cameras[cameraName]) {
  65989. //this._indicesForCamera.splice(index, 1);
  65990. this._cameras[cameraName] = null;
  65991. }
  65992. }
  65993. };
  65994. /**
  65995. * Enables the effect on given cameras
  65996. * @param cameras The camera to enable.
  65997. */
  65998. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65999. var _this = this;
  66000. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66001. if (!cams) {
  66002. return;
  66003. }
  66004. for (var i = 0; i < cams.length; i++) {
  66005. var camera = cams[i];
  66006. var cameraName = camera.name;
  66007. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66008. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66009. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66010. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66011. });
  66012. }
  66013. }
  66014. }
  66015. };
  66016. /**
  66017. * Disables the effect on the given cameras
  66018. * @param cameras The camera to disable.
  66019. */
  66020. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66021. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66022. if (!cams) {
  66023. return;
  66024. }
  66025. for (var i = 0; i < cams.length; i++) {
  66026. var camera = cams[i];
  66027. var cameraName = camera.name;
  66028. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66029. camera.detachPostProcess(postProcess);
  66030. });
  66031. }
  66032. };
  66033. /**
  66034. * Gets a list of the post processes contained in the effect.
  66035. * @param camera The camera to get the post processes on.
  66036. * @returns The list of the post processes in the effect.
  66037. */
  66038. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66039. if (this._singleInstance) {
  66040. return this._postProcesses[0];
  66041. }
  66042. else {
  66043. if (!camera) {
  66044. return null;
  66045. }
  66046. return this._postProcesses[camera.name];
  66047. }
  66048. };
  66049. return PostProcessRenderEffect;
  66050. }());
  66051. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66052. })(BABYLON || (BABYLON = {}));
  66053. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66054. var BABYLON;
  66055. (function (BABYLON) {
  66056. var PostProcessRenderPipeline = /** @class */ (function () {
  66057. function PostProcessRenderPipeline(engine, name) {
  66058. this.engine = engine;
  66059. this._name = name;
  66060. this._renderEffects = {};
  66061. this._renderEffectsForIsolatedPass = new Array();
  66062. this._cameras = [];
  66063. }
  66064. PostProcessRenderPipeline.prototype.getClassName = function () {
  66065. return "PostProcessRenderPipeline";
  66066. };
  66067. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66068. get: function () {
  66069. for (var renderEffectName in this._renderEffects) {
  66070. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66071. if (!this._renderEffects[renderEffectName].isSupported) {
  66072. return false;
  66073. }
  66074. }
  66075. }
  66076. return true;
  66077. },
  66078. enumerable: true,
  66079. configurable: true
  66080. });
  66081. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66082. this._renderEffects[renderEffect._name] = renderEffect;
  66083. };
  66084. // private
  66085. PostProcessRenderPipeline.prototype._rebuild = function () {
  66086. };
  66087. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66088. var renderEffects = this._renderEffects[renderEffectName];
  66089. if (!renderEffects) {
  66090. return;
  66091. }
  66092. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66093. };
  66094. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66095. var renderEffects = this._renderEffects[renderEffectName];
  66096. if (!renderEffects) {
  66097. return;
  66098. }
  66099. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66100. };
  66101. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66102. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66103. if (!cams) {
  66104. return;
  66105. }
  66106. var indicesToDelete = [];
  66107. var i;
  66108. for (i = 0; i < cams.length; i++) {
  66109. var camera = cams[i];
  66110. var cameraName = camera.name;
  66111. if (this._cameras.indexOf(camera) === -1) {
  66112. this._cameras[cameraName] = camera;
  66113. }
  66114. else if (unique) {
  66115. indicesToDelete.push(i);
  66116. }
  66117. }
  66118. for (i = 0; i < indicesToDelete.length; i++) {
  66119. cameras.splice(indicesToDelete[i], 1);
  66120. }
  66121. for (var renderEffectName in this._renderEffects) {
  66122. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66123. this._renderEffects[renderEffectName]._attachCameras(cams);
  66124. }
  66125. }
  66126. };
  66127. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66128. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66129. if (!cams) {
  66130. return;
  66131. }
  66132. for (var renderEffectName in this._renderEffects) {
  66133. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66134. this._renderEffects[renderEffectName]._detachCameras(cams);
  66135. }
  66136. }
  66137. for (var i = 0; i < cams.length; i++) {
  66138. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66139. }
  66140. };
  66141. PostProcessRenderPipeline.prototype._update = function () {
  66142. for (var renderEffectName in this._renderEffects) {
  66143. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66144. this._renderEffects[renderEffectName]._update();
  66145. }
  66146. }
  66147. for (var i = 0; i < this._cameras.length; i++) {
  66148. var cameraName = this._cameras[i].name;
  66149. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66150. this._renderEffectsForIsolatedPass[cameraName]._update();
  66151. }
  66152. }
  66153. };
  66154. PostProcessRenderPipeline.prototype._reset = function () {
  66155. this._renderEffects = {};
  66156. this._renderEffectsForIsolatedPass = new Array();
  66157. };
  66158. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66159. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  66160. var effectKeys = Object.keys(this._renderEffects);
  66161. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66162. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66163. if (postProcesses) {
  66164. postProcesses[0].samples = 4;
  66165. return true;
  66166. }
  66167. }
  66168. return false;
  66169. };
  66170. PostProcessRenderPipeline.prototype.dispose = function () {
  66171. // Must be implemented by children
  66172. };
  66173. __decorate([
  66174. BABYLON.serialize()
  66175. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66176. return PostProcessRenderPipeline;
  66177. }());
  66178. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66179. })(BABYLON || (BABYLON = {}));
  66180. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66181. var BABYLON;
  66182. (function (BABYLON) {
  66183. /**
  66184. * This represents a depth renderer in Babylon.
  66185. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66186. */
  66187. var DepthRenderer = /** @class */ (function () {
  66188. /**
  66189. * Instantiates a depth renderer
  66190. * @param scene The scene the renderer belongs to
  66191. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66192. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66193. */
  66194. function DepthRenderer(scene, type, camera) {
  66195. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66196. if (camera === void 0) { camera = null; }
  66197. var _this = this;
  66198. this._scene = scene;
  66199. this._camera = camera;
  66200. var engine = scene.getEngine();
  66201. // Render target
  66202. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66203. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66204. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66205. this._depthMap.refreshRate = 1;
  66206. this._depthMap.renderParticles = false;
  66207. this._depthMap.renderList = null;
  66208. // Camera to get depth map from to support multiple concurrent cameras
  66209. this._depthMap.activeCamera = this._camera;
  66210. this._depthMap.ignoreCameraViewport = true;
  66211. this._depthMap.useCameraPostProcesses = false;
  66212. // set default depth value to 1.0 (far away)
  66213. this._depthMap.onClearObservable.add(function (engine) {
  66214. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66215. });
  66216. // Custom render function
  66217. var renderSubMesh = function (subMesh) {
  66218. var mesh = subMesh.getRenderingMesh();
  66219. var scene = _this._scene;
  66220. var engine = scene.getEngine();
  66221. var material = subMesh.getMaterial();
  66222. if (!material) {
  66223. return;
  66224. }
  66225. // Culling and reverse (right handed system)
  66226. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66227. // Managing instances
  66228. var batch = mesh._getInstancesRenderList(subMesh._id);
  66229. if (batch.mustReturn) {
  66230. return;
  66231. }
  66232. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66233. var camera = _this._camera || scene.activeCamera;
  66234. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66235. engine.enableEffect(_this._effect);
  66236. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66237. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66238. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66239. // Alpha test
  66240. if (material && material.needAlphaTesting()) {
  66241. var alphaTexture = material.getAlphaTestTexture();
  66242. if (alphaTexture) {
  66243. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66244. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66245. }
  66246. }
  66247. // Bones
  66248. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66249. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66250. }
  66251. // Draw
  66252. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66253. }
  66254. };
  66255. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66256. var index;
  66257. if (depthOnlySubMeshes.length) {
  66258. engine.setColorWrite(false);
  66259. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66260. renderSubMesh(depthOnlySubMeshes.data[index]);
  66261. }
  66262. engine.setColorWrite(true);
  66263. }
  66264. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66265. renderSubMesh(opaqueSubMeshes.data[index]);
  66266. }
  66267. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66268. renderSubMesh(alphaTestSubMeshes.data[index]);
  66269. }
  66270. };
  66271. }
  66272. /**
  66273. * Creates the depth rendering effect and checks if the effect is ready.
  66274. * @param subMesh The submesh to be used to render the depth map of
  66275. * @param useInstances If multiple world instances should be used
  66276. * @returns if the depth renderer is ready to render the depth map
  66277. */
  66278. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66279. var material = subMesh.getMaterial();
  66280. if (material.disableDepthWrite) {
  66281. return false;
  66282. }
  66283. var defines = [];
  66284. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66285. var mesh = subMesh.getMesh();
  66286. // Alpha test
  66287. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66288. defines.push("#define ALPHATEST");
  66289. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66290. attribs.push(BABYLON.VertexBuffer.UVKind);
  66291. defines.push("#define UV1");
  66292. }
  66293. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66294. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66295. defines.push("#define UV2");
  66296. }
  66297. }
  66298. // Bones
  66299. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66300. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66301. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66302. if (mesh.numBoneInfluencers > 4) {
  66303. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66304. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66305. }
  66306. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66307. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66308. }
  66309. else {
  66310. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66311. }
  66312. // Instances
  66313. if (useInstances) {
  66314. defines.push("#define INSTANCES");
  66315. attribs.push("world0");
  66316. attribs.push("world1");
  66317. attribs.push("world2");
  66318. attribs.push("world3");
  66319. }
  66320. // Get correct effect
  66321. var join = defines.join("\n");
  66322. if (this._cachedDefines !== join) {
  66323. this._cachedDefines = join;
  66324. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66325. }
  66326. return this._effect.isReady();
  66327. };
  66328. /**
  66329. * Gets the texture which the depth map will be written to.
  66330. * @returns The depth map texture
  66331. */
  66332. DepthRenderer.prototype.getDepthMap = function () {
  66333. return this._depthMap;
  66334. };
  66335. /**
  66336. * Disposes of the depth renderer.
  66337. */
  66338. DepthRenderer.prototype.dispose = function () {
  66339. this._depthMap.dispose();
  66340. };
  66341. return DepthRenderer;
  66342. }());
  66343. BABYLON.DepthRenderer = DepthRenderer;
  66344. })(BABYLON || (BABYLON = {}));
  66345. //# sourceMappingURL=babylon.depthRenderer.js.map
  66346. var BABYLON;
  66347. (function (BABYLON) {
  66348. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66349. __extends(SSAORenderingPipeline, _super);
  66350. /**
  66351. * @constructor
  66352. * @param {string} name - The rendering pipeline name
  66353. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66354. * @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 }
  66355. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66356. */
  66357. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66358. var _this = _super.call(this, scene.getEngine(), name) || this;
  66359. // Members
  66360. /**
  66361. * The PassPostProcess id in the pipeline that contains the original scene color
  66362. * @type {string}
  66363. */
  66364. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66365. /**
  66366. * The SSAO PostProcess id in the pipeline
  66367. * @type {string}
  66368. */
  66369. _this.SSAORenderEffect = "SSAORenderEffect";
  66370. /**
  66371. * The horizontal blur PostProcess id in the pipeline
  66372. * @type {string}
  66373. */
  66374. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66375. /**
  66376. * The vertical blur PostProcess id in the pipeline
  66377. * @type {string}
  66378. */
  66379. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66380. /**
  66381. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66382. * @type {string}
  66383. */
  66384. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66385. /**
  66386. * The output strength of the SSAO post-process. Default value is 1.0.
  66387. * @type {number}
  66388. */
  66389. _this.totalStrength = 1.0;
  66390. /**
  66391. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66392. * @type {number}
  66393. */
  66394. _this.radius = 0.0001;
  66395. /**
  66396. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66397. * Must not be equal to fallOff and superior to fallOff.
  66398. * Default value is 0.975
  66399. * @type {number}
  66400. */
  66401. _this.area = 0.0075;
  66402. /**
  66403. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66404. * Must not be equal to area and inferior to area.
  66405. * Default value is 0.0
  66406. * @type {number}
  66407. */
  66408. _this.fallOff = 0.000001;
  66409. /**
  66410. * The base color of the SSAO post-process
  66411. * The final result is "base + ssao" between [0, 1]
  66412. * @type {number}
  66413. */
  66414. _this.base = 0.5;
  66415. _this._firstUpdate = true;
  66416. _this._scene = scene;
  66417. // Set up assets
  66418. _this._createRandomTexture();
  66419. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66420. var ssaoRatio = ratio.ssaoRatio || ratio;
  66421. var combineRatio = ratio.combineRatio || ratio;
  66422. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66423. _this._createSSAOPostProcess(ssaoRatio);
  66424. _this._createBlurPostProcess(ssaoRatio);
  66425. _this._createSSAOCombinePostProcess(combineRatio);
  66426. // Set up pipeline
  66427. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66428. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66429. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66431. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66432. // Finish
  66433. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66434. if (cameras)
  66435. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66436. return _this;
  66437. }
  66438. // Public Methods
  66439. /**
  66440. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66441. */
  66442. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66443. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66444. for (var i = 0; i < this._scene.cameras.length; i++) {
  66445. var camera = this._scene.cameras[i];
  66446. this._originalColorPostProcess.dispose(camera);
  66447. this._ssaoPostProcess.dispose(camera);
  66448. this._blurHPostProcess.dispose(camera);
  66449. this._blurVPostProcess.dispose(camera);
  66450. this._ssaoCombinePostProcess.dispose(camera);
  66451. }
  66452. this._randomTexture.dispose();
  66453. if (disableDepthRender)
  66454. this._scene.disableDepthRenderer();
  66455. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66456. _super.prototype.dispose.call(this);
  66457. };
  66458. // Private Methods
  66459. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66460. var _this = this;
  66461. var size = 16;
  66462. 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);
  66463. 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);
  66464. this._blurHPostProcess.onActivateObservable.add(function () {
  66465. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66466. _this._blurHPostProcess.kernel = size * dw;
  66467. });
  66468. this._blurVPostProcess.onActivateObservable.add(function () {
  66469. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66470. _this._blurVPostProcess.kernel = size * dw;
  66471. });
  66472. };
  66473. SSAORenderingPipeline.prototype._rebuild = function () {
  66474. this._firstUpdate = true;
  66475. _super.prototype._rebuild.call(this);
  66476. };
  66477. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66478. var _this = this;
  66479. var numSamples = 16;
  66480. var sampleSphere = [
  66481. 0.5381, 0.1856, -0.4319,
  66482. 0.1379, 0.2486, 0.4430,
  66483. 0.3371, 0.5679, -0.0057,
  66484. -0.6999, -0.0451, -0.0019,
  66485. 0.0689, -0.1598, -0.8547,
  66486. 0.0560, 0.0069, -0.1843,
  66487. -0.0146, 0.1402, 0.0762,
  66488. 0.0100, -0.1924, -0.0344,
  66489. -0.3577, -0.5301, -0.4358,
  66490. -0.3169, 0.1063, 0.0158,
  66491. 0.0103, -0.5869, 0.0046,
  66492. -0.0897, -0.4940, 0.3287,
  66493. 0.7119, -0.0154, -0.0918,
  66494. -0.0533, 0.0596, -0.5411,
  66495. 0.0352, -0.0631, 0.5460,
  66496. -0.4776, 0.2847, -0.0271
  66497. ];
  66498. var samplesFactor = 1.0 / numSamples;
  66499. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66500. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66501. "area", "fallOff", "base", "range", "viewport"
  66502. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66503. this._ssaoPostProcess.onApply = function (effect) {
  66504. if (_this._firstUpdate) {
  66505. effect.setArray3("sampleSphere", sampleSphere);
  66506. effect.setFloat("samplesFactor", samplesFactor);
  66507. effect.setFloat("randTextureTiles", 4.0);
  66508. }
  66509. effect.setFloat("totalStrength", _this.totalStrength);
  66510. effect.setFloat("radius", _this.radius);
  66511. effect.setFloat("area", _this.area);
  66512. effect.setFloat("fallOff", _this.fallOff);
  66513. effect.setFloat("base", _this.base);
  66514. effect.setTexture("textureSampler", _this._depthTexture);
  66515. effect.setTexture("randomSampler", _this._randomTexture);
  66516. };
  66517. };
  66518. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66519. var _this = this;
  66520. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66521. this._ssaoCombinePostProcess.onApply = function (effect) {
  66522. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66523. };
  66524. };
  66525. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66526. var size = 512;
  66527. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66528. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66529. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66530. var context = this._randomTexture.getContext();
  66531. var rand = function (min, max) {
  66532. return Math.random() * (max - min) + min;
  66533. };
  66534. var randVector = BABYLON.Vector3.Zero();
  66535. for (var x = 0; x < size; x++) {
  66536. for (var y = 0; y < size; y++) {
  66537. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66538. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66539. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66540. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66541. context.fillRect(x, y, 1, 1);
  66542. }
  66543. }
  66544. this._randomTexture.update(false);
  66545. };
  66546. __decorate([
  66547. BABYLON.serialize()
  66548. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66549. __decorate([
  66550. BABYLON.serialize()
  66551. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66552. __decorate([
  66553. BABYLON.serialize()
  66554. ], SSAORenderingPipeline.prototype, "area", void 0);
  66555. __decorate([
  66556. BABYLON.serialize()
  66557. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66558. __decorate([
  66559. BABYLON.serialize()
  66560. ], SSAORenderingPipeline.prototype, "base", void 0);
  66561. return SSAORenderingPipeline;
  66562. }(BABYLON.PostProcessRenderPipeline));
  66563. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66564. })(BABYLON || (BABYLON = {}));
  66565. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66566. var BABYLON;
  66567. (function (BABYLON) {
  66568. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66569. __extends(SSAO2RenderingPipeline, _super);
  66570. /**
  66571. * @constructor
  66572. * @param {string} name - The rendering pipeline name
  66573. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66574. * @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 }
  66575. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66576. */
  66577. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66578. var _this = _super.call(this, scene.getEngine(), name) || this;
  66579. // Members
  66580. /**
  66581. * The PassPostProcess id in the pipeline that contains the original scene color
  66582. * @type {string}
  66583. */
  66584. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66585. /**
  66586. * The SSAO PostProcess id in the pipeline
  66587. * @type {string}
  66588. */
  66589. _this.SSAORenderEffect = "SSAORenderEffect";
  66590. /**
  66591. * The horizontal blur PostProcess id in the pipeline
  66592. * @type {string}
  66593. */
  66594. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66595. /**
  66596. * The vertical blur PostProcess id in the pipeline
  66597. * @type {string}
  66598. */
  66599. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66600. /**
  66601. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66602. * @type {string}
  66603. */
  66604. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66605. /**
  66606. * The output strength of the SSAO post-process. Default value is 1.0.
  66607. * @type {number}
  66608. */
  66609. _this.totalStrength = 1.0;
  66610. /**
  66611. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66612. * @type {number}
  66613. */
  66614. _this.maxZ = 100.0;
  66615. /**
  66616. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66617. * @type {number}
  66618. */
  66619. _this.minZAspect = 0.2;
  66620. /**
  66621. * Number of samples used for the SSAO calculations. Default value is 8
  66622. * @type {number}
  66623. */
  66624. _this._samples = 8;
  66625. /**
  66626. * Are we using bilateral blur ?
  66627. * @type {boolean}
  66628. */
  66629. _this._expensiveBlur = true;
  66630. /**
  66631. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66632. * @type {number}
  66633. */
  66634. _this.radius = 2.0;
  66635. /**
  66636. * The base color of the SSAO post-process
  66637. * The final result is "base + ssao" between [0, 1]
  66638. * @type {number}
  66639. */
  66640. _this.base = 0.1;
  66641. _this._firstUpdate = true;
  66642. _this._scene = scene;
  66643. if (!_this.isSupported) {
  66644. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66645. return _this;
  66646. }
  66647. var ssaoRatio = ratio.ssaoRatio || ratio;
  66648. var blurRatio = ratio.blurRatio || ratio;
  66649. // Set up assets
  66650. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66651. _this._createRandomTexture();
  66652. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66653. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66654. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66655. _this._createSSAOPostProcess(1.0);
  66656. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66657. _this._createSSAOCombinePostProcess(blurRatio);
  66658. // Set up pipeline
  66659. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66660. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66661. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66662. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66663. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66664. // Finish
  66665. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66666. if (cameras)
  66667. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66668. return _this;
  66669. }
  66670. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66671. get: function () {
  66672. return this._samples;
  66673. },
  66674. set: function (n) {
  66675. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66676. this._samples = n;
  66677. this._sampleSphere = this._generateHemisphere();
  66678. this._firstUpdate = true;
  66679. },
  66680. enumerable: true,
  66681. configurable: true
  66682. });
  66683. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66684. get: function () {
  66685. return this._expensiveBlur;
  66686. },
  66687. set: function (b) {
  66688. 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"]);
  66689. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66690. this._expensiveBlur = b;
  66691. this._firstUpdate = true;
  66692. },
  66693. enumerable: true,
  66694. configurable: true
  66695. });
  66696. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66697. /**
  66698. * Support test.
  66699. * @type {boolean}
  66700. */
  66701. get: function () {
  66702. var engine = BABYLON.Engine.LastCreatedEngine;
  66703. if (!engine) {
  66704. return false;
  66705. }
  66706. return engine.getCaps().drawBuffersExtension;
  66707. },
  66708. enumerable: true,
  66709. configurable: true
  66710. });
  66711. // Public Methods
  66712. /**
  66713. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66714. */
  66715. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66716. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66717. for (var i = 0; i < this._scene.cameras.length; i++) {
  66718. var camera = this._scene.cameras[i];
  66719. this._originalColorPostProcess.dispose(camera);
  66720. this._ssaoPostProcess.dispose(camera);
  66721. this._blurHPostProcess.dispose(camera);
  66722. this._blurVPostProcess.dispose(camera);
  66723. this._ssaoCombinePostProcess.dispose(camera);
  66724. }
  66725. this._randomTexture.dispose();
  66726. if (disableGeometryBufferRenderer)
  66727. this._scene.disableGeometryBufferRenderer();
  66728. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66729. _super.prototype.dispose.call(this);
  66730. };
  66731. // Private Methods
  66732. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66733. var _this = this;
  66734. this._samplerOffsets = [];
  66735. var expensive = this.expensiveBlur;
  66736. for (var i = -8; i < 8; i++) {
  66737. this._samplerOffsets.push(i * 2 + 0.5);
  66738. }
  66739. 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");
  66740. this._blurHPostProcess.onApply = function (effect) {
  66741. if (!_this._scene.activeCamera) {
  66742. return;
  66743. }
  66744. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66745. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66746. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66747. effect.setFloat("radius", _this.radius);
  66748. effect.setTexture("depthSampler", _this._depthTexture);
  66749. if (_this._firstUpdate) {
  66750. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66751. }
  66752. };
  66753. 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");
  66754. this._blurVPostProcess.onApply = function (effect) {
  66755. if (!_this._scene.activeCamera) {
  66756. return;
  66757. }
  66758. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66759. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66760. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66761. effect.setFloat("radius", _this.radius);
  66762. effect.setTexture("depthSampler", _this._depthTexture);
  66763. if (_this._firstUpdate) {
  66764. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66765. _this._firstUpdate = false;
  66766. }
  66767. };
  66768. };
  66769. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66770. this._firstUpdate = true;
  66771. _super.prototype._rebuild.call(this);
  66772. };
  66773. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66774. var numSamples = this.samples;
  66775. var result = [];
  66776. var vector, scale;
  66777. var rand = function (min, max) {
  66778. return Math.random() * (max - min) + min;
  66779. };
  66780. var i = 0;
  66781. while (i < numSamples) {
  66782. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66783. vector.normalize();
  66784. scale = i / numSamples;
  66785. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66786. vector.scaleInPlace(scale);
  66787. result.push(vector.x, vector.y, vector.z);
  66788. i++;
  66789. }
  66790. return result;
  66791. };
  66792. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66793. var _this = this;
  66794. var numSamples = this.samples;
  66795. this._sampleSphere = this._generateHemisphere();
  66796. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66797. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66798. "base", "range", "projection", "near", "far", "texelSize",
  66799. "xViewport", "yViewport", "maxZ", "minZAspect"
  66800. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66801. this._ssaoPostProcess.onApply = function (effect) {
  66802. if (_this._firstUpdate) {
  66803. effect.setArray3("sampleSphere", _this._sampleSphere);
  66804. effect.setFloat("randTextureTiles", 4.0);
  66805. }
  66806. if (!_this._scene.activeCamera) {
  66807. return;
  66808. }
  66809. effect.setFloat("samplesFactor", 1 / _this.samples);
  66810. effect.setFloat("totalStrength", _this.totalStrength);
  66811. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66812. effect.setFloat("radius", _this.radius);
  66813. effect.setFloat("maxZ", _this.maxZ);
  66814. effect.setFloat("minZAspect", _this.minZAspect);
  66815. effect.setFloat("base", _this.base);
  66816. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66817. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66818. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66819. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66820. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66821. effect.setTexture("textureSampler", _this._depthTexture);
  66822. effect.setTexture("normalSampler", _this._normalTexture);
  66823. effect.setTexture("randomSampler", _this._randomTexture);
  66824. };
  66825. };
  66826. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66827. var _this = this;
  66828. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66829. this._ssaoCombinePostProcess.onApply = function (effect) {
  66830. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66831. };
  66832. };
  66833. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66834. var size = 512;
  66835. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66836. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66837. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66838. var context = this._randomTexture.getContext();
  66839. var rand = function (min, max) {
  66840. return Math.random() * (max - min) + min;
  66841. };
  66842. var randVector = BABYLON.Vector3.Zero();
  66843. for (var x = 0; x < size; x++) {
  66844. for (var y = 0; y < size; y++) {
  66845. randVector.x = rand(0.0, 1.0);
  66846. randVector.y = rand(0.0, 1.0);
  66847. randVector.z = 0.0;
  66848. randVector.normalize();
  66849. randVector.scaleInPlace(255);
  66850. randVector.x = Math.floor(randVector.x);
  66851. randVector.y = Math.floor(randVector.y);
  66852. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66853. context.fillRect(x, y, 1, 1);
  66854. }
  66855. }
  66856. this._randomTexture.update(false);
  66857. };
  66858. __decorate([
  66859. BABYLON.serialize()
  66860. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66861. __decorate([
  66862. BABYLON.serialize()
  66863. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66864. __decorate([
  66865. BABYLON.serialize()
  66866. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66867. __decorate([
  66868. BABYLON.serialize("samples")
  66869. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66870. __decorate([
  66871. BABYLON.serialize("expensiveBlur")
  66872. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66873. __decorate([
  66874. BABYLON.serialize()
  66875. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66876. __decorate([
  66877. BABYLON.serialize()
  66878. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66879. return SSAO2RenderingPipeline;
  66880. }(BABYLON.PostProcessRenderPipeline));
  66881. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66882. })(BABYLON || (BABYLON = {}));
  66883. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66884. // BABYLON.JS Chromatic Aberration GLSL Shader
  66885. // Author: Olivier Guyot
  66886. // Separates very slightly R, G and B colors on the edges of the screen
  66887. // Inspired by Francois Tarlier & Martins Upitis
  66888. var BABYLON;
  66889. (function (BABYLON) {
  66890. var LensRenderingPipeline = /** @class */ (function (_super) {
  66891. __extends(LensRenderingPipeline, _super);
  66892. /**
  66893. * @constructor
  66894. *
  66895. * Effect parameters are as follow:
  66896. * {
  66897. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66898. * edge_blur: number; // from 0 to x (1 for realism)
  66899. * distortion: number; // from 0 to x (1 for realism)
  66900. * grain_amount: number; // from 0 to 1
  66901. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66902. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66903. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66904. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66905. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66906. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66907. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66908. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66909. * }
  66910. * Note: if an effect parameter is unset, effect is disabled
  66911. *
  66912. * @param {string} name - The rendering pipeline name
  66913. * @param {object} parameters - An object containing all parameters (see above)
  66914. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66915. * @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)
  66916. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66917. */
  66918. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66919. if (ratio === void 0) { ratio = 1.0; }
  66920. var _this = _super.call(this, scene.getEngine(), name) || this;
  66921. // Lens effects can be of the following:
  66922. // - chromatic aberration (slight shift of RGB colors)
  66923. // - blur on the edge of the lens
  66924. // - lens distortion
  66925. // - depth-of-field blur & highlights enhancing
  66926. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66927. // - grain effect (noise or custom texture)
  66928. // Two additional texture samplers are needed:
  66929. // - depth map (for depth-of-field)
  66930. // - grain texture
  66931. /**
  66932. * The chromatic aberration PostProcess id in the pipeline
  66933. * @type {string}
  66934. */
  66935. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66936. /**
  66937. * The highlights enhancing PostProcess id in the pipeline
  66938. * @type {string}
  66939. */
  66940. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66941. /**
  66942. * The depth-of-field PostProcess id in the pipeline
  66943. * @type {string}
  66944. */
  66945. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66946. _this._scene = scene;
  66947. // Fetch texture samplers
  66948. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66949. if (parameters.grain_texture) {
  66950. _this._grainTexture = parameters.grain_texture;
  66951. }
  66952. else {
  66953. _this._createGrainTexture();
  66954. }
  66955. // save parameters
  66956. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66957. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66958. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66959. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66960. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66961. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66962. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66963. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66964. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66965. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66966. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66967. // Create effects
  66968. _this._createChromaticAberrationPostProcess(ratio);
  66969. _this._createHighlightsPostProcess(ratio);
  66970. _this._createDepthOfFieldPostProcess(ratio / 4);
  66971. // Set up pipeline
  66972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66975. if (_this._highlightsGain === -1) {
  66976. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66977. }
  66978. // Finish
  66979. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66980. if (cameras) {
  66981. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66982. }
  66983. return _this;
  66984. }
  66985. // public methods (self explanatory)
  66986. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66987. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66988. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66989. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66990. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66991. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66992. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66993. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66994. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66995. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66996. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66997. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66998. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66999. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67000. };
  67001. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67002. this._highlightsPostProcess.updateEffect();
  67003. };
  67004. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67005. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67006. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67007. this._highlightsGain = amount;
  67008. };
  67009. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67010. if (this._highlightsGain === -1) {
  67011. this._highlightsGain = 1.0;
  67012. }
  67013. this._highlightsThreshold = amount;
  67014. };
  67015. LensRenderingPipeline.prototype.disableHighlights = function () {
  67016. this._highlightsGain = -1;
  67017. };
  67018. /**
  67019. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67020. */
  67021. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67022. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67023. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67024. this._chromaticAberrationPostProcess = null;
  67025. this._highlightsPostProcess = null;
  67026. this._depthOfFieldPostProcess = null;
  67027. this._grainTexture.dispose();
  67028. if (disableDepthRender)
  67029. this._scene.disableDepthRenderer();
  67030. };
  67031. // colors shifting and distortion
  67032. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67033. var _this = this;
  67034. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67035. [], // samplers
  67036. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67037. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67038. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67039. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67040. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67041. effect.setFloat('radialIntensity', 1);
  67042. effect.setFloat2('direction', 17, 17);
  67043. effect.setFloat2('centerPosition', 0.5, 0.5);
  67044. };
  67045. };
  67046. // highlights enhancing
  67047. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67048. var _this = this;
  67049. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67050. [], // samplers
  67051. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67052. this._highlightsPostProcess.onApply = function (effect) {
  67053. effect.setFloat('gain', _this._highlightsGain);
  67054. effect.setFloat('threshold', _this._highlightsThreshold);
  67055. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67056. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67057. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67058. };
  67059. };
  67060. // colors shifting and distortion
  67061. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67062. var _this = this;
  67063. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67064. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67065. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67066. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67067. this._depthOfFieldPostProcess.onApply = function (effect) {
  67068. effect.setTexture("depthSampler", _this._depthTexture);
  67069. effect.setTexture("grainSampler", _this._grainTexture);
  67070. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67071. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67072. effect.setFloat('grain_amount', _this._grainAmount);
  67073. effect.setBool('blur_noise', _this._blurNoise);
  67074. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67075. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67076. effect.setFloat('distortion', _this._distortion);
  67077. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67078. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67079. effect.setFloat('aperture', _this._dofAperture);
  67080. effect.setFloat('darken', _this._dofDarken);
  67081. effect.setFloat('edge_blur', _this._edgeBlur);
  67082. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67083. if (_this._scene.activeCamera) {
  67084. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67085. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67086. }
  67087. };
  67088. };
  67089. // creates a black and white random noise texture, 512x512
  67090. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67091. var size = 512;
  67092. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67093. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67094. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67095. var context = this._grainTexture.getContext();
  67096. var rand = function (min, max) {
  67097. return Math.random() * (max - min) + min;
  67098. };
  67099. var value;
  67100. for (var x = 0; x < size; x++) {
  67101. for (var y = 0; y < size; y++) {
  67102. value = Math.floor(rand(0.42, 0.58) * 255);
  67103. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67104. context.fillRect(x, y, 1, 1);
  67105. }
  67106. }
  67107. this._grainTexture.update(false);
  67108. };
  67109. return LensRenderingPipeline;
  67110. }(BABYLON.PostProcessRenderPipeline));
  67111. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67112. })(BABYLON || (BABYLON = {}));
  67113. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67114. var BABYLON;
  67115. (function (BABYLON) {
  67116. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67117. __extends(StandardRenderingPipeline, _super);
  67118. /**
  67119. * @constructor
  67120. * @param {string} name - The rendering pipeline name
  67121. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67122. * @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)
  67123. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67124. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67125. */
  67126. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67127. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67128. var _this = _super.call(this, scene.getEngine(), name) || this;
  67129. _this.downSampleX4PostProcess = null;
  67130. _this.brightPassPostProcess = null;
  67131. _this.blurHPostProcesses = [];
  67132. _this.blurVPostProcesses = [];
  67133. _this.textureAdderPostProcess = null;
  67134. _this.volumetricLightPostProcess = null;
  67135. _this.volumetricLightSmoothXPostProcess = null;
  67136. _this.volumetricLightSmoothYPostProcess = null;
  67137. _this.volumetricLightMergePostProces = null;
  67138. _this.volumetricLightFinalPostProcess = null;
  67139. _this.luminancePostProcess = null;
  67140. _this.luminanceDownSamplePostProcesses = [];
  67141. _this.hdrPostProcess = null;
  67142. _this.textureAdderFinalPostProcess = null;
  67143. _this.lensFlareFinalPostProcess = null;
  67144. _this.hdrFinalPostProcess = null;
  67145. _this.lensFlarePostProcess = null;
  67146. _this.lensFlareComposePostProcess = null;
  67147. _this.motionBlurPostProcess = null;
  67148. _this.depthOfFieldPostProcess = null;
  67149. // Values
  67150. _this.brightThreshold = 1.0;
  67151. _this.blurWidth = 512.0;
  67152. _this.horizontalBlur = false;
  67153. _this.exposure = 1.0;
  67154. _this.lensTexture = null;
  67155. _this.volumetricLightCoefficient = 0.2;
  67156. _this.volumetricLightPower = 4.0;
  67157. _this.volumetricLightBlurScale = 64.0;
  67158. _this.sourceLight = null;
  67159. _this.hdrMinimumLuminance = 1.0;
  67160. _this.hdrDecreaseRate = 0.5;
  67161. _this.hdrIncreaseRate = 0.5;
  67162. _this.lensColorTexture = null;
  67163. _this.lensFlareStrength = 20.0;
  67164. _this.lensFlareGhostDispersal = 1.4;
  67165. _this.lensFlareHaloWidth = 0.7;
  67166. _this.lensFlareDistortionStrength = 16.0;
  67167. _this.lensStarTexture = null;
  67168. _this.lensFlareDirtTexture = null;
  67169. _this.depthOfFieldDistance = 10.0;
  67170. _this.depthOfFieldBlurWidth = 64.0;
  67171. _this.motionStrength = 1.0;
  67172. // IAnimatable
  67173. _this.animations = [];
  67174. _this._currentDepthOfFieldSource = null;
  67175. _this._hdrCurrentLuminance = 1.0;
  67176. // Getters and setters
  67177. _this._bloomEnabled = true;
  67178. _this._depthOfFieldEnabled = false;
  67179. _this._vlsEnabled = false;
  67180. _this._lensFlareEnabled = false;
  67181. _this._hdrEnabled = false;
  67182. _this._motionBlurEnabled = false;
  67183. _this._motionBlurSamples = 64.0;
  67184. _this._volumetricLightStepsCount = 50.0;
  67185. _this._cameras = cameras || [];
  67186. // Initialize
  67187. _this._scene = scene;
  67188. _this._basePostProcess = originalPostProcess;
  67189. _this._ratio = ratio;
  67190. // Misc
  67191. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67192. // Finish
  67193. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67194. _this._buildPipeline();
  67195. return _this;
  67196. }
  67197. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67198. get: function () {
  67199. return this._bloomEnabled;
  67200. },
  67201. set: function (enabled) {
  67202. if (this._bloomEnabled === enabled) {
  67203. return;
  67204. }
  67205. this._bloomEnabled = enabled;
  67206. this._buildPipeline();
  67207. },
  67208. enumerable: true,
  67209. configurable: true
  67210. });
  67211. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67212. get: function () {
  67213. return this._depthOfFieldEnabled;
  67214. },
  67215. set: function (enabled) {
  67216. if (this._depthOfFieldEnabled === enabled) {
  67217. return;
  67218. }
  67219. this._depthOfFieldEnabled = enabled;
  67220. this._buildPipeline();
  67221. },
  67222. enumerable: true,
  67223. configurable: true
  67224. });
  67225. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67226. get: function () {
  67227. return this._lensFlareEnabled;
  67228. },
  67229. set: function (enabled) {
  67230. if (this._lensFlareEnabled === enabled) {
  67231. return;
  67232. }
  67233. this._lensFlareEnabled = enabled;
  67234. this._buildPipeline();
  67235. },
  67236. enumerable: true,
  67237. configurable: true
  67238. });
  67239. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67240. get: function () {
  67241. return this._hdrEnabled;
  67242. },
  67243. set: function (enabled) {
  67244. if (this._hdrEnabled === enabled) {
  67245. return;
  67246. }
  67247. this._hdrEnabled = enabled;
  67248. this._buildPipeline();
  67249. },
  67250. enumerable: true,
  67251. configurable: true
  67252. });
  67253. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67254. get: function () {
  67255. return this._vlsEnabled;
  67256. },
  67257. set: function (enabled) {
  67258. if (this._vlsEnabled === enabled) {
  67259. return;
  67260. }
  67261. if (enabled) {
  67262. var geometry = this._scene.enableGeometryBufferRenderer();
  67263. if (!geometry) {
  67264. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67265. return;
  67266. }
  67267. }
  67268. this._vlsEnabled = enabled;
  67269. this._buildPipeline();
  67270. },
  67271. enumerable: true,
  67272. configurable: true
  67273. });
  67274. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67275. get: function () {
  67276. return this._motionBlurEnabled;
  67277. },
  67278. set: function (enabled) {
  67279. if (this._motionBlurEnabled === enabled) {
  67280. return;
  67281. }
  67282. this._motionBlurEnabled = enabled;
  67283. this._buildPipeline();
  67284. },
  67285. enumerable: true,
  67286. configurable: true
  67287. });
  67288. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67289. get: function () {
  67290. return this._volumetricLightStepsCount;
  67291. },
  67292. set: function (count) {
  67293. if (this.volumetricLightPostProcess) {
  67294. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67295. }
  67296. this._volumetricLightStepsCount = count;
  67297. },
  67298. enumerable: true,
  67299. configurable: true
  67300. });
  67301. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67302. get: function () {
  67303. return this._motionBlurSamples;
  67304. },
  67305. set: function (samples) {
  67306. if (this.motionBlurPostProcess) {
  67307. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67308. }
  67309. this._motionBlurSamples = samples;
  67310. },
  67311. enumerable: true,
  67312. configurable: true
  67313. });
  67314. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67315. var _this = this;
  67316. var ratio = this._ratio;
  67317. var scene = this._scene;
  67318. this._disposePostProcesses();
  67319. this._reset();
  67320. // Create pass post-process
  67321. if (!this._basePostProcess) {
  67322. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67323. this.originalPostProcess.onApply = function (effect) {
  67324. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67325. };
  67326. }
  67327. else {
  67328. this.originalPostProcess = this._basePostProcess;
  67329. }
  67330. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67331. this._currentDepthOfFieldSource = this.originalPostProcess;
  67332. if (this._vlsEnabled) {
  67333. // Create volumetric light
  67334. this._createVolumetricLightPostProcess(scene, ratio);
  67335. // Create volumetric light final post-process
  67336. 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);
  67337. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67338. }
  67339. if (this._bloomEnabled) {
  67340. // Create down sample X4 post-process
  67341. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67342. // Create bright pass post-process
  67343. this._createBrightPassPostProcess(scene, ratio / 2);
  67344. // Create gaussian blur post-processes (down sampling blurs)
  67345. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67346. // Create texture adder post-process
  67347. this._createTextureAdderPostProcess(scene, ratio);
  67348. // Create depth-of-field source post-process
  67349. 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);
  67350. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67351. }
  67352. if (this._lensFlareEnabled) {
  67353. // Create lens flare post-process
  67354. this._createLensFlarePostProcess(scene, ratio);
  67355. // Create depth-of-field source post-process post lens-flare and disable it now
  67356. 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);
  67357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67358. }
  67359. if (this._hdrEnabled) {
  67360. // Create luminance
  67361. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67362. // Create HDR
  67363. this._createHdrPostProcess(scene, ratio);
  67364. // Create depth-of-field source post-process post hdr and disable it now
  67365. 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);
  67366. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67367. }
  67368. if (this._depthOfFieldEnabled) {
  67369. // Create gaussian blur used by depth-of-field
  67370. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67371. // Create depth-of-field post-process
  67372. this._createDepthOfFieldPostProcess(scene, ratio);
  67373. }
  67374. if (this._motionBlurEnabled) {
  67375. // Create motion blur post-process
  67376. this._createMotionBlurPostProcess(scene, ratio);
  67377. }
  67378. if (this._cameras !== null) {
  67379. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67380. }
  67381. };
  67382. // Down Sample X4 Post-Processs
  67383. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67384. var _this = this;
  67385. var downSampleX4Offsets = new Array(32);
  67386. 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);
  67387. this.downSampleX4PostProcess.onApply = function (effect) {
  67388. var id = 0;
  67389. var width = _this.downSampleX4PostProcess.width;
  67390. var height = _this.downSampleX4PostProcess.height;
  67391. for (var i = -2; i < 2; i++) {
  67392. for (var j = -2; j < 2; j++) {
  67393. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67394. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67395. id += 2;
  67396. }
  67397. }
  67398. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67399. };
  67400. // Add to pipeline
  67401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67402. };
  67403. // Brightpass Post-Process
  67404. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67405. var _this = this;
  67406. var brightOffsets = new Array(8);
  67407. 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);
  67408. this.brightPassPostProcess.onApply = function (effect) {
  67409. var sU = (1.0 / _this.brightPassPostProcess.width);
  67410. var sV = (1.0 / _this.brightPassPostProcess.height);
  67411. brightOffsets[0] = -0.5 * sU;
  67412. brightOffsets[1] = 0.5 * sV;
  67413. brightOffsets[2] = 0.5 * sU;
  67414. brightOffsets[3] = 0.5 * sV;
  67415. brightOffsets[4] = -0.5 * sU;
  67416. brightOffsets[5] = -0.5 * sV;
  67417. brightOffsets[6] = 0.5 * sU;
  67418. brightOffsets[7] = -0.5 * sV;
  67419. effect.setArray2("dsOffsets", brightOffsets);
  67420. effect.setFloat("brightThreshold", _this.brightThreshold);
  67421. };
  67422. // Add to pipeline
  67423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67424. };
  67425. // Create blur H&V post-processes
  67426. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67427. var _this = this;
  67428. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67429. var engine = scene.getEngine();
  67430. 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);
  67431. 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);
  67432. blurX.onActivateObservable.add(function () {
  67433. var dw = blurX.width / engine.getRenderWidth();
  67434. blurX.kernel = _this[blurWidthKey] * dw;
  67435. });
  67436. blurY.onActivateObservable.add(function () {
  67437. var dw = blurY.height / engine.getRenderHeight();
  67438. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67439. });
  67440. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67442. this.blurHPostProcesses.push(blurX);
  67443. this.blurVPostProcesses.push(blurY);
  67444. };
  67445. // Create texture adder post-process
  67446. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67447. var _this = this;
  67448. 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);
  67449. this.textureAdderPostProcess.onApply = function (effect) {
  67450. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67451. effect.setTexture("lensSampler", _this.lensTexture);
  67452. effect.setFloat("exposure", _this.exposure);
  67453. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67454. };
  67455. // Add to pipeline
  67456. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67457. };
  67458. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67459. var _this = this;
  67460. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67461. geometryRenderer.enablePosition = true;
  67462. var geometry = geometryRenderer.getGBuffer();
  67463. // Base post-process
  67464. 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));
  67465. var depthValues = BABYLON.Vector2.Zero();
  67466. this.volumetricLightPostProcess.onApply = function (effect) {
  67467. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67468. var generator = _this.sourceLight.getShadowGenerator();
  67469. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67470. effect.setTexture("positionSampler", geometry.textures[2]);
  67471. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67472. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67473. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67474. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67475. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67476. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67477. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67478. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67479. effect.setVector2("depthValues", depthValues);
  67480. }
  67481. };
  67482. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67483. // Smooth
  67484. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67485. // Merge
  67486. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67487. this.volumetricLightMergePostProces.onApply = function (effect) {
  67488. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67489. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67490. };
  67491. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67492. };
  67493. // Create luminance
  67494. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67495. var _this = this;
  67496. // Create luminance
  67497. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67498. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67499. var offsets = [];
  67500. this.luminancePostProcess.onApply = function (effect) {
  67501. var sU = (1.0 / _this.luminancePostProcess.width);
  67502. var sV = (1.0 / _this.luminancePostProcess.height);
  67503. offsets[0] = -0.5 * sU;
  67504. offsets[1] = 0.5 * sV;
  67505. offsets[2] = 0.5 * sU;
  67506. offsets[3] = 0.5 * sV;
  67507. offsets[4] = -0.5 * sU;
  67508. offsets[5] = -0.5 * sV;
  67509. offsets[6] = 0.5 * sU;
  67510. offsets[7] = -0.5 * sV;
  67511. effect.setArray2("lumOffsets", offsets);
  67512. };
  67513. // Add to pipeline
  67514. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67515. // Create down sample luminance
  67516. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67517. var size = Math.pow(3, i);
  67518. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67519. if (i === 0) {
  67520. defines += "#define FINAL_DOWN_SAMPLER";
  67521. }
  67522. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67523. this.luminanceDownSamplePostProcesses.push(postProcess);
  67524. }
  67525. // Create callbacks and add effects
  67526. var lastLuminance = this.luminancePostProcess;
  67527. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67528. var downSampleOffsets = new Array(18);
  67529. pp.onApply = function (effect) {
  67530. if (!lastLuminance) {
  67531. return;
  67532. }
  67533. var id = 0;
  67534. for (var x = -1; x < 2; x++) {
  67535. for (var y = -1; y < 2; y++) {
  67536. downSampleOffsets[id] = x / lastLuminance.width;
  67537. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67538. id += 2;
  67539. }
  67540. }
  67541. effect.setArray2("dsOffsets", downSampleOffsets);
  67542. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67543. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67544. lastLuminance = _this.luminancePostProcess;
  67545. }
  67546. else {
  67547. lastLuminance = pp;
  67548. }
  67549. };
  67550. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67551. pp.onAfterRender = function (effect) {
  67552. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67553. 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);
  67554. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67555. };
  67556. }
  67557. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67558. });
  67559. };
  67560. // Create HDR post-process
  67561. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67562. var _this = this;
  67563. 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);
  67564. var outputLiminance = 1;
  67565. var time = 0;
  67566. var lastTime = 0;
  67567. this.hdrPostProcess.onApply = function (effect) {
  67568. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67569. time += scene.getEngine().getDeltaTime();
  67570. if (outputLiminance < 0) {
  67571. outputLiminance = _this._hdrCurrentLuminance;
  67572. }
  67573. else {
  67574. var dt = (lastTime - time) / 1000.0;
  67575. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67576. outputLiminance += _this.hdrDecreaseRate * dt;
  67577. }
  67578. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67579. outputLiminance -= _this.hdrIncreaseRate * dt;
  67580. }
  67581. else {
  67582. outputLiminance = _this._hdrCurrentLuminance;
  67583. }
  67584. }
  67585. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67586. effect.setFloat("averageLuminance", outputLiminance);
  67587. lastTime = time;
  67588. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67589. };
  67590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67591. };
  67592. // Create lens flare post-process
  67593. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67594. var _this = this;
  67595. 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);
  67596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67597. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67598. 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);
  67599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67600. var resolution = new BABYLON.Vector2(0, 0);
  67601. // Lens flare
  67602. this.lensFlarePostProcess.onApply = function (effect) {
  67603. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67604. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67605. effect.setFloat("strength", _this.lensFlareStrength);
  67606. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67607. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67608. // Shift
  67609. resolution.x = _this.lensFlarePostProcess.width;
  67610. resolution.y = _this.lensFlarePostProcess.height;
  67611. effect.setVector2("resolution", resolution);
  67612. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67613. };
  67614. // Compose
  67615. 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);
  67616. 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);
  67617. this.lensFlareComposePostProcess.onApply = function (effect) {
  67618. if (!_this._scene.activeCamera) {
  67619. return;
  67620. }
  67621. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67622. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67623. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67624. // Lens start rotation matrix
  67625. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67626. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67627. 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));
  67628. camRot *= 4.0;
  67629. 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);
  67630. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67631. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67632. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67633. };
  67634. };
  67635. // Create depth-of-field post-process
  67636. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67637. var _this = this;
  67638. 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);
  67639. this.depthOfFieldPostProcess.onApply = function (effect) {
  67640. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67641. effect.setTexture("depthSampler", _this._getDepthTexture());
  67642. effect.setFloat("distance", _this.depthOfFieldDistance);
  67643. };
  67644. // Add to pipeline
  67645. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67646. };
  67647. // Create motion blur post-process
  67648. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67649. var _this = this;
  67650. 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);
  67651. var motionScale = 0;
  67652. var prevViewProjection = BABYLON.Matrix.Identity();
  67653. var invViewProjection = BABYLON.Matrix.Identity();
  67654. var viewProjection = BABYLON.Matrix.Identity();
  67655. var screenSize = BABYLON.Vector2.Zero();
  67656. this.motionBlurPostProcess.onApply = function (effect) {
  67657. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67658. viewProjection.invertToRef(invViewProjection);
  67659. effect.setMatrix("inverseViewProjection", invViewProjection);
  67660. effect.setMatrix("prevViewProjection", prevViewProjection);
  67661. prevViewProjection = viewProjection;
  67662. screenSize.x = _this.motionBlurPostProcess.width;
  67663. screenSize.y = _this.motionBlurPostProcess.height;
  67664. effect.setVector2("screenSize", screenSize);
  67665. motionScale = scene.getEngine().getFps() / 60.0;
  67666. effect.setFloat("motionScale", motionScale);
  67667. effect.setFloat("motionStrength", _this.motionStrength);
  67668. effect.setTexture("depthSampler", _this._getDepthTexture());
  67669. };
  67670. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67671. };
  67672. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67673. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67674. var renderer = this._scene.enableGeometryBufferRenderer();
  67675. return renderer.getGBuffer().textures[0];
  67676. }
  67677. return this._scene.enableDepthRenderer().getDepthMap();
  67678. };
  67679. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67680. for (var i = 0; i < this._cameras.length; i++) {
  67681. var camera = this._cameras[i];
  67682. if (this.originalPostProcess) {
  67683. this.originalPostProcess.dispose(camera);
  67684. }
  67685. if (this.downSampleX4PostProcess) {
  67686. this.downSampleX4PostProcess.dispose(camera);
  67687. }
  67688. if (this.brightPassPostProcess) {
  67689. this.brightPassPostProcess.dispose(camera);
  67690. }
  67691. if (this.textureAdderPostProcess) {
  67692. this.textureAdderPostProcess.dispose(camera);
  67693. }
  67694. if (this.textureAdderFinalPostProcess) {
  67695. this.textureAdderFinalPostProcess.dispose(camera);
  67696. }
  67697. if (this.volumetricLightPostProcess) {
  67698. this.volumetricLightPostProcess.dispose(camera);
  67699. }
  67700. if (this.volumetricLightSmoothXPostProcess) {
  67701. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67702. }
  67703. if (this.volumetricLightSmoothYPostProcess) {
  67704. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67705. }
  67706. if (this.volumetricLightMergePostProces) {
  67707. this.volumetricLightMergePostProces.dispose(camera);
  67708. }
  67709. if (this.volumetricLightFinalPostProcess) {
  67710. this.volumetricLightFinalPostProcess.dispose(camera);
  67711. }
  67712. if (this.lensFlarePostProcess) {
  67713. this.lensFlarePostProcess.dispose(camera);
  67714. }
  67715. if (this.lensFlareComposePostProcess) {
  67716. this.lensFlareComposePostProcess.dispose(camera);
  67717. }
  67718. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67719. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67720. }
  67721. if (this.luminancePostProcess) {
  67722. this.luminancePostProcess.dispose(camera);
  67723. }
  67724. if (this.hdrPostProcess) {
  67725. this.hdrPostProcess.dispose(camera);
  67726. }
  67727. if (this.hdrFinalPostProcess) {
  67728. this.hdrFinalPostProcess.dispose(camera);
  67729. }
  67730. if (this.depthOfFieldPostProcess) {
  67731. this.depthOfFieldPostProcess.dispose(camera);
  67732. }
  67733. if (this.motionBlurPostProcess) {
  67734. this.motionBlurPostProcess.dispose(camera);
  67735. }
  67736. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67737. this.blurHPostProcesses[j].dispose(camera);
  67738. }
  67739. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67740. this.blurVPostProcesses[j].dispose(camera);
  67741. }
  67742. }
  67743. this.originalPostProcess = null;
  67744. this.downSampleX4PostProcess = null;
  67745. this.brightPassPostProcess = null;
  67746. this.textureAdderPostProcess = null;
  67747. this.textureAdderFinalPostProcess = null;
  67748. this.volumetricLightPostProcess = null;
  67749. this.volumetricLightSmoothXPostProcess = null;
  67750. this.volumetricLightSmoothYPostProcess = null;
  67751. this.volumetricLightMergePostProces = null;
  67752. this.volumetricLightFinalPostProcess = null;
  67753. this.lensFlarePostProcess = null;
  67754. this.lensFlareComposePostProcess = null;
  67755. this.luminancePostProcess = null;
  67756. this.hdrPostProcess = null;
  67757. this.hdrFinalPostProcess = null;
  67758. this.depthOfFieldPostProcess = null;
  67759. this.motionBlurPostProcess = null;
  67760. this.luminanceDownSamplePostProcesses = [];
  67761. this.blurHPostProcesses = [];
  67762. this.blurVPostProcesses = [];
  67763. };
  67764. // Dispose
  67765. StandardRenderingPipeline.prototype.dispose = function () {
  67766. this._disposePostProcesses();
  67767. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67768. _super.prototype.dispose.call(this);
  67769. };
  67770. // Serialize rendering pipeline
  67771. StandardRenderingPipeline.prototype.serialize = function () {
  67772. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67773. serializationObject.customType = "StandardRenderingPipeline";
  67774. return serializationObject;
  67775. };
  67776. /**
  67777. * Static members
  67778. */
  67779. // Parse serialized pipeline
  67780. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67781. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67782. };
  67783. // Luminance steps
  67784. StandardRenderingPipeline.LuminanceSteps = 6;
  67785. __decorate([
  67786. BABYLON.serialize()
  67787. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67788. __decorate([
  67789. BABYLON.serialize()
  67790. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67791. __decorate([
  67792. BABYLON.serialize()
  67793. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67794. __decorate([
  67795. BABYLON.serialize()
  67796. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67797. __decorate([
  67798. BABYLON.serializeAsTexture("lensTexture")
  67799. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67800. __decorate([
  67801. BABYLON.serialize()
  67802. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67803. __decorate([
  67804. BABYLON.serialize()
  67805. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67806. __decorate([
  67807. BABYLON.serialize()
  67808. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67809. __decorate([
  67810. BABYLON.serialize()
  67811. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67812. __decorate([
  67813. BABYLON.serialize()
  67814. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67815. __decorate([
  67816. BABYLON.serialize()
  67817. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67818. __decorate([
  67819. BABYLON.serializeAsTexture("lensColorTexture")
  67820. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67821. __decorate([
  67822. BABYLON.serialize()
  67823. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67824. __decorate([
  67825. BABYLON.serialize()
  67826. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67827. __decorate([
  67828. BABYLON.serialize()
  67829. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67830. __decorate([
  67831. BABYLON.serialize()
  67832. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67833. __decorate([
  67834. BABYLON.serializeAsTexture("lensStarTexture")
  67835. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67836. __decorate([
  67837. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67838. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67839. __decorate([
  67840. BABYLON.serialize()
  67841. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67842. __decorate([
  67843. BABYLON.serialize()
  67844. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67845. __decorate([
  67846. BABYLON.serialize()
  67847. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67848. __decorate([
  67849. BABYLON.serialize()
  67850. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67851. __decorate([
  67852. BABYLON.serialize()
  67853. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67854. __decorate([
  67855. BABYLON.serialize()
  67856. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67857. __decorate([
  67858. BABYLON.serialize()
  67859. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67860. __decorate([
  67861. BABYLON.serialize()
  67862. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67863. __decorate([
  67864. BABYLON.serialize()
  67865. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67866. __decorate([
  67867. BABYLON.serialize()
  67868. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67869. __decorate([
  67870. BABYLON.serialize()
  67871. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67872. __decorate([
  67873. BABYLON.serialize()
  67874. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67875. return StandardRenderingPipeline;
  67876. }(BABYLON.PostProcessRenderPipeline));
  67877. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67878. })(BABYLON || (BABYLON = {}));
  67879. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67880. var BABYLON;
  67881. (function (BABYLON) {
  67882. var FxaaPostProcess = /** @class */ (function (_super) {
  67883. __extends(FxaaPostProcess, _super);
  67884. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67885. if (camera === void 0) { camera = null; }
  67886. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67887. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67888. _this.onApplyObservable.add(function (effect) {
  67889. var texelSize = _this.texelSize;
  67890. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67891. });
  67892. return _this;
  67893. }
  67894. return FxaaPostProcess;
  67895. }(BABYLON.PostProcess));
  67896. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67897. })(BABYLON || (BABYLON = {}));
  67898. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67899. var BABYLON;
  67900. (function (BABYLON) {
  67901. /**
  67902. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  67903. */
  67904. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  67905. __extends(ChromaticAberrationPostProcess, _super);
  67906. /**
  67907. * Creates a new instance of @see ChromaticAberrationPostProcess
  67908. * @param name The name of the effect.
  67909. * @param screenWidth The width of the screen to apply the effect on.
  67910. * @param screenHeight The height of the screen to apply the effect on.
  67911. * @param options The required width/height ratio to downsize to before computing the render pass.
  67912. * @param camera The camera to apply the render pass to.
  67913. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67914. * @param engine The engine which the post process will be applied. (default: current engine)
  67915. * @param reusable If the post process can be reused on the same frame. (default: false)
  67916. * @param textureType Type of textures used when performing the post process. (default: 0)
  67917. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  67918. */
  67919. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67920. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67921. if (blockCompilation === void 0) { blockCompilation = false; }
  67922. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  67923. /**
  67924. * The amount of seperation of rgb channels (default: 30)
  67925. */
  67926. _this.aberrationAmount = 30;
  67927. /**
  67928. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  67929. */
  67930. _this.radialIntensity = 0;
  67931. /**
  67932. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  67933. */
  67934. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  67935. /**
  67936. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  67937. */
  67938. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  67939. _this.onApplyObservable.add(function (effect) {
  67940. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  67941. effect.setFloat('screen_width', screenWidth);
  67942. effect.setFloat('screen_height', screenHeight);
  67943. effect.setFloat('radialIntensity', _this.radialIntensity);
  67944. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  67945. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  67946. });
  67947. return _this;
  67948. }
  67949. return ChromaticAberrationPostProcess;
  67950. }(BABYLON.PostProcess));
  67951. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  67952. })(BABYLON || (BABYLON = {}));
  67953. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  67954. var BABYLON;
  67955. (function (BABYLON) {
  67956. /**
  67957. * The SharpenPostProcess applies a sharpen kernel to every pixel
  67958. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67959. */
  67960. var SharpenPostProcess = /** @class */ (function (_super) {
  67961. __extends(SharpenPostProcess, _super);
  67962. /**
  67963. * Creates a new instance of @see ConvolutionPostProcess
  67964. * @param name The name of the effect.
  67965. * @param options The required width/height ratio to downsize to before computing the render pass.
  67966. * @param camera The camera to apply the render pass to.
  67967. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67968. * @param engine The engine which the post process will be applied. (default: current engine)
  67969. * @param reusable If the post process can be reused on the same frame. (default: false)
  67970. * @param textureType Type of textures used when performing the post process. (default: 0)
  67971. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  67972. */
  67973. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67974. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67975. if (blockCompilation === void 0) { blockCompilation = false; }
  67976. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  67977. /**
  67978. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  67979. */
  67980. _this.colorAmount = 1.0;
  67981. /**
  67982. * How much sharpness should be applied (default: 0.3)
  67983. */
  67984. _this.edgeAmount = 0.3;
  67985. _this.onApply = function (effect) {
  67986. effect.setFloat2("screenSize", _this.width, _this.height);
  67987. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  67988. };
  67989. return _this;
  67990. }
  67991. return SharpenPostProcess;
  67992. }(BABYLON.PostProcess));
  67993. BABYLON.SharpenPostProcess = SharpenPostProcess;
  67994. })(BABYLON || (BABYLON = {}));
  67995. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  67996. var BABYLON;
  67997. (function (BABYLON) {
  67998. /**
  67999. * The Blur Post Process which blurs an image based on a kernel and direction.
  68000. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68001. */
  68002. var BlurPostProcess = /** @class */ (function (_super) {
  68003. __extends(BlurPostProcess, _super);
  68004. /**
  68005. * Creates a new instance of @see BlurPostProcess
  68006. * @param name The name of the effect.
  68007. * @param direction The direction in which to blur the image.
  68008. * @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.
  68009. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68010. * @param camera The camera to apply the render pass to.
  68011. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68012. * @param engine The engine which the post process will be applied. (default: current engine)
  68013. * @param reusable If the post process can be reused on the same frame. (default: false)
  68014. * @param textureType Type of textures used when performing the post process. (default: 0)
  68015. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68016. */
  68017. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68019. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68020. if (defines === void 0) { defines = ""; }
  68021. if (blockCompilation === void 0) { blockCompilation = false; }
  68022. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  68023. _this.direction = direction;
  68024. _this.blockCompilation = blockCompilation;
  68025. _this._packedFloat = false;
  68026. _this._staticDefines = "";
  68027. _this._staticDefines = defines;
  68028. _this.onApplyObservable.add(function (effect) {
  68029. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68030. });
  68031. _this.kernel = kernel;
  68032. return _this;
  68033. }
  68034. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68035. /**
  68036. * Gets the length in pixels of the blur sample region
  68037. */
  68038. get: function () {
  68039. return this._idealKernel;
  68040. },
  68041. /**
  68042. * Sets the length in pixels of the blur sample region
  68043. */
  68044. set: function (v) {
  68045. if (this._idealKernel === v) {
  68046. return;
  68047. }
  68048. v = Math.max(v, 1);
  68049. this._idealKernel = v;
  68050. this._kernel = this._nearestBestKernel(v);
  68051. if (!this.blockCompilation) {
  68052. this._updateParameters();
  68053. }
  68054. },
  68055. enumerable: true,
  68056. configurable: true
  68057. });
  68058. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68059. /**
  68060. * Gets wether or not the blur is unpacking/repacking floats
  68061. */
  68062. get: function () {
  68063. return this._packedFloat;
  68064. },
  68065. /**
  68066. * Sets wether or not the blur needs to unpack/repack floats
  68067. */
  68068. set: function (v) {
  68069. if (this._packedFloat === v) {
  68070. return;
  68071. }
  68072. this._packedFloat = v;
  68073. if (!this.blockCompilation) {
  68074. this._updateParameters();
  68075. }
  68076. },
  68077. enumerable: true,
  68078. configurable: true
  68079. });
  68080. /**
  68081. * Updates the effect with the current post process compile time values and recompiles the shader.
  68082. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68083. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68084. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68085. * @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
  68086. * @param onCompiled Called when the shader has been compiled.
  68087. * @param onError Called if there is an error when compiling a shader.
  68088. */
  68089. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68090. if (defines === void 0) { defines = null; }
  68091. if (uniforms === void 0) { uniforms = null; }
  68092. if (samplers === void 0) { samplers = null; }
  68093. this._updateParameters(onCompiled, onError);
  68094. };
  68095. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68096. // Generate sampling offsets and weights
  68097. var N = this._kernel;
  68098. var centerIndex = (N - 1) / 2;
  68099. // Generate Gaussian sampling weights over kernel
  68100. var offsets = [];
  68101. var weights = [];
  68102. var totalWeight = 0;
  68103. for (var i = 0; i < N; i++) {
  68104. var u = i / (N - 1);
  68105. var w = this._gaussianWeight(u * 2.0 - 1);
  68106. offsets[i] = (i - centerIndex);
  68107. weights[i] = w;
  68108. totalWeight += w;
  68109. }
  68110. // Normalize weights
  68111. for (var i = 0; i < weights.length; i++) {
  68112. weights[i] /= totalWeight;
  68113. }
  68114. // Optimize: combine samples to take advantage of hardware linear sampling
  68115. // Walk from left to center, combining pairs (symmetrically)
  68116. var linearSamplingWeights = [];
  68117. var linearSamplingOffsets = [];
  68118. var linearSamplingMap = [];
  68119. for (var i = 0; i <= centerIndex; i += 2) {
  68120. var j = Math.min(i + 1, Math.floor(centerIndex));
  68121. var singleCenterSample = i === j;
  68122. if (singleCenterSample) {
  68123. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68124. }
  68125. else {
  68126. var sharedCell = j === centerIndex;
  68127. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68128. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68129. if (offsetLinear === 0) {
  68130. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68131. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68132. }
  68133. else {
  68134. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68135. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68136. }
  68137. }
  68138. }
  68139. for (var i = 0; i < linearSamplingMap.length; i++) {
  68140. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68141. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68142. }
  68143. // Replace with optimized
  68144. offsets = linearSamplingOffsets;
  68145. weights = linearSamplingWeights;
  68146. // Generate shaders
  68147. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68148. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68149. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68150. var defines = "";
  68151. defines += this._staticDefines;
  68152. for (var i = 0; i < varyingCount; i++) {
  68153. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68154. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68155. }
  68156. var depCount = 0;
  68157. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68158. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68159. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68160. depCount++;
  68161. }
  68162. if (this.packedFloat) {
  68163. defines += "#define PACKEDFLOAT 1";
  68164. }
  68165. _super.prototype.updateEffect.call(this, defines, null, null, {
  68166. varyingCount: varyingCount,
  68167. depCount: depCount
  68168. }, onCompiled, onError);
  68169. };
  68170. /**
  68171. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68172. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68173. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68174. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68175. * The gaps between physical kernels are compensated for in the weighting of the samples
  68176. * @param idealKernel Ideal blur kernel.
  68177. * @return Nearest best kernel.
  68178. */
  68179. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68180. var v = Math.round(idealKernel);
  68181. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68182. var k = _a[_i];
  68183. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68184. return Math.max(k, 3);
  68185. }
  68186. }
  68187. return Math.max(v, 3);
  68188. };
  68189. /**
  68190. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68191. * @param x The point on the Gaussian distribution to sample.
  68192. * @return the value of the Gaussian function at x.
  68193. */
  68194. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68195. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68196. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68197. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68198. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68199. // truncated at around 1.3% of peak strength.
  68200. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68201. var sigma = (1 / 3);
  68202. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68203. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68204. var weight = (1.0 / denominator) * Math.exp(exponent);
  68205. return weight;
  68206. };
  68207. /**
  68208. * Generates a string that can be used as a floating point number in GLSL.
  68209. * @param x Value to print.
  68210. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68211. * @return GLSL float string.
  68212. */
  68213. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68214. if (decimalFigures === void 0) { decimalFigures = 8; }
  68215. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68216. };
  68217. return BlurPostProcess;
  68218. }(BABYLON.PostProcess));
  68219. BABYLON.BlurPostProcess = BlurPostProcess;
  68220. })(BABYLON || (BABYLON = {}));
  68221. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68222. var BABYLON;
  68223. (function (BABYLON) {
  68224. /**
  68225. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68226. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68227. * based on samples that have a large difference in distance than the center pixel.
  68228. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68229. */
  68230. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68231. __extends(DepthOfFieldBlurPostProcess, _super);
  68232. /**
  68233. * Creates a new instance of @see CircleOfConfusionPostProcess
  68234. * @param name The name of the effect.
  68235. * @param scene The scene the effect belongs to.
  68236. * @param direction The direction the blur should be applied.
  68237. * @param kernel The size of the kernel used to blur.
  68238. * @param options The required width/height ratio to downsize to before computing the render pass.
  68239. * @param camera The camera to apply the render pass to.
  68240. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68241. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68242. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68243. * @param engine The engine which the post process will be applied. (default: current engine)
  68244. * @param reusable If the post process can be reused on the same frame. (default: false)
  68245. * @param textureType Type of textures used when performing the post process. (default: 0)
  68246. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68247. */
  68248. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  68249. if (imageToBlur === void 0) { imageToBlur = null; }
  68250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68251. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68252. if (blockCompilation === void 0) { blockCompilation = false; }
  68253. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  68254. _this.direction = direction;
  68255. _this.onApplyObservable.add(function (effect) {
  68256. if (imageToBlur != null) {
  68257. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68258. }
  68259. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68260. if (scene.activeCamera) {
  68261. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68262. }
  68263. });
  68264. return _this;
  68265. }
  68266. return DepthOfFieldBlurPostProcess;
  68267. }(BABYLON.BlurPostProcess));
  68268. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68269. })(BABYLON || (BABYLON = {}));
  68270. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68271. var BABYLON;
  68272. (function (BABYLON) {
  68273. /**
  68274. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68275. */
  68276. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68277. __extends(DepthOfFieldMergePostProcess, _super);
  68278. /**
  68279. * Creates a new instance of @see CircleOfConfusionPostProcess
  68280. * @param name The name of the effect.
  68281. * @param original The non-blurred image to be modified
  68282. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68283. * @param blurSteps Incrimental bluring post processes.
  68284. * @param options The required width/height ratio to downsize to before computing the render pass.
  68285. * @param camera The camera to apply the render pass to.
  68286. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68287. * @param engine The engine which the post process will be applied. (default: current engine)
  68288. * @param reusable If the post process can be reused on the same frame. (default: false)
  68289. * @param textureType Type of textures used when performing the post process. (default: 0)
  68290. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68291. */
  68292. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68293. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68294. if (blockCompilation === void 0) { blockCompilation = false; }
  68295. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  68296. _this.blurSteps = blurSteps;
  68297. _this.onApplyObservable.add(function (effect) {
  68298. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68299. effect.setTextureFromPostProcess("originalSampler", original);
  68300. blurSteps.forEach(function (step, index) {
  68301. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68302. });
  68303. });
  68304. if (!blockCompilation) {
  68305. _this.updateEffect();
  68306. }
  68307. return _this;
  68308. }
  68309. /**
  68310. * Updates the effect with the current post process compile time values and recompiles the shader.
  68311. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68312. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68313. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68314. * @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
  68315. * @param onCompiled Called when the shader has been compiled.
  68316. * @param onError Called if there is an error when compiling a shader.
  68317. */
  68318. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68319. if (defines === void 0) { defines = null; }
  68320. if (uniforms === void 0) { uniforms = null; }
  68321. if (samplers === void 0) { samplers = null; }
  68322. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  68323. };
  68324. return DepthOfFieldMergePostProcess;
  68325. }(BABYLON.PostProcess));
  68326. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68327. })(BABYLON || (BABYLON = {}));
  68328. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68329. var BABYLON;
  68330. (function (BABYLON) {
  68331. /**
  68332. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68333. */
  68334. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68335. __extends(CircleOfConfusionPostProcess, _super);
  68336. /**
  68337. * Creates a new instance of @see CircleOfConfusionPostProcess
  68338. * @param name The name of the effect.
  68339. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  68340. * @param options The required width/height ratio to downsize to before computing the render pass.
  68341. * @param camera The camera to apply the render pass to.
  68342. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68343. * @param engine The engine which the post process will be applied. (default: current engine)
  68344. * @param reusable If the post process can be reused on the same frame. (default: false)
  68345. * @param textureType Type of textures used when performing the post process. (default: 0)
  68346. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68347. */
  68348. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68349. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68350. if (blockCompilation === void 0) { blockCompilation = false; }
  68351. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68352. /**
  68353. * 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.
  68354. */
  68355. _this.lensSize = 50;
  68356. /**
  68357. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68358. */
  68359. _this.fStop = 1.4;
  68360. /**
  68361. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68362. */
  68363. _this.focusDistance = 2000;
  68364. /**
  68365. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68366. */
  68367. _this.focalLength = 50;
  68368. _this._depthTexture = null;
  68369. _this._depthTexture = depthTexture;
  68370. _this.onApplyObservable.add(function (effect) {
  68371. if (!_this._depthTexture) {
  68372. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  68373. return;
  68374. }
  68375. effect.setTexture("depthSampler", _this._depthTexture);
  68376. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68377. var aperture = _this.lensSize / _this.fStop;
  68378. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68379. effect.setFloat('focusDistance', _this.focusDistance);
  68380. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68381. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  68382. });
  68383. return _this;
  68384. }
  68385. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  68386. /**
  68387. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  68388. */
  68389. set: function (value) {
  68390. this._depthTexture = value;
  68391. },
  68392. enumerable: true,
  68393. configurable: true
  68394. });
  68395. return CircleOfConfusionPostProcess;
  68396. }(BABYLON.PostProcess));
  68397. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68398. })(BABYLON || (BABYLON = {}));
  68399. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68400. var BABYLON;
  68401. (function (BABYLON) {
  68402. /**
  68403. * Specifies the level of max blur that should be applied when using the depth of field effect
  68404. */
  68405. var DepthOfFieldEffectBlurLevel;
  68406. (function (DepthOfFieldEffectBlurLevel) {
  68407. /**
  68408. * Subtle blur
  68409. */
  68410. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68411. /**
  68412. * Medium blur
  68413. */
  68414. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68415. /**
  68416. * Large blur
  68417. */
  68418. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68419. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68420. ;
  68421. /**
  68422. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68423. */
  68424. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68425. __extends(DepthOfFieldEffect, _super);
  68426. /**
  68427. * Creates a new instance of @see DepthOfFieldEffect
  68428. * @param scene The scene the effect belongs to.
  68429. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  68430. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68431. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68432. */
  68433. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  68434. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68435. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68436. if (blockCompilation === void 0) { blockCompilation = false; }
  68437. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68438. return _this._effects;
  68439. }, true) || this;
  68440. _this._effects = [];
  68441. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68442. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68443. // Capture circle of confusion texture
  68444. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68445. _this._depthOfFieldPass.autoClear = false;
  68446. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  68447. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68448. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68449. _this._depthOfFieldBlurY = [];
  68450. _this._depthOfFieldBlurX = [];
  68451. var blurCount = 1;
  68452. var kernelSize = 15;
  68453. switch (blurLevel) {
  68454. case DepthOfFieldEffectBlurLevel.High: {
  68455. blurCount = 3;
  68456. kernelSize = 51;
  68457. break;
  68458. }
  68459. case DepthOfFieldEffectBlurLevel.Medium: {
  68460. blurCount = 2;
  68461. kernelSize = 31;
  68462. break;
  68463. }
  68464. default: {
  68465. kernelSize = 15;
  68466. blurCount = 1;
  68467. break;
  68468. }
  68469. }
  68470. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68471. for (var i = 0; i < blurCount; i++) {
  68472. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68473. blurY.autoClear = false;
  68474. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68475. blurX.autoClear = false;
  68476. _this._depthOfFieldBlurY.push(blurY);
  68477. _this._depthOfFieldBlurX.push(blurX);
  68478. }
  68479. // Merge blurred images with original image based on circleOfConfusion
  68480. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68481. _this._depthOfFieldMerge.autoClear = false;
  68482. // Set all post processes on the effect.
  68483. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68484. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68485. _this._effects.push(_this._depthOfFieldBlurY[i]);
  68486. _this._effects.push(_this._depthOfFieldBlurX[i]);
  68487. }
  68488. _this._effects.push(_this._depthOfFieldMerge);
  68489. return _this;
  68490. }
  68491. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68492. get: function () {
  68493. return this._circleOfConfusion.focalLength;
  68494. },
  68495. /**
  68496. * The focal the length of the camera used in the effect
  68497. */
  68498. set: function (value) {
  68499. this._circleOfConfusion.focalLength = value;
  68500. },
  68501. enumerable: true,
  68502. configurable: true
  68503. });
  68504. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68505. get: function () {
  68506. return this._circleOfConfusion.fStop;
  68507. },
  68508. /**
  68509. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68510. */
  68511. set: function (value) {
  68512. this._circleOfConfusion.fStop = value;
  68513. },
  68514. enumerable: true,
  68515. configurable: true
  68516. });
  68517. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68518. get: function () {
  68519. return this._circleOfConfusion.focusDistance;
  68520. },
  68521. /**
  68522. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68523. */
  68524. set: function (value) {
  68525. this._circleOfConfusion.focusDistance = value;
  68526. },
  68527. enumerable: true,
  68528. configurable: true
  68529. });
  68530. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68531. get: function () {
  68532. return this._circleOfConfusion.lensSize;
  68533. },
  68534. /**
  68535. * 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.
  68536. */
  68537. set: function (value) {
  68538. this._circleOfConfusion.lensSize = value;
  68539. },
  68540. enumerable: true,
  68541. configurable: true
  68542. });
  68543. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  68544. /**
  68545. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  68546. */
  68547. set: function (value) {
  68548. this._circleOfConfusion.depthTexture = value;
  68549. },
  68550. enumerable: true,
  68551. configurable: true
  68552. });
  68553. /**
  68554. * Disposes each of the internal effects for a given camera.
  68555. * @param camera The camera to dispose the effect on.
  68556. */
  68557. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68558. this._depthOfFieldPass.dispose(camera);
  68559. this._circleOfConfusion.dispose(camera);
  68560. this._depthOfFieldBlurX.forEach(function (element) {
  68561. element.dispose(camera);
  68562. });
  68563. this._depthOfFieldBlurY.forEach(function (element) {
  68564. element.dispose(camera);
  68565. });
  68566. this._depthOfFieldMerge.dispose(camera);
  68567. };
  68568. /**
  68569. * Internal
  68570. */
  68571. DepthOfFieldEffect.prototype._updateEffects = function () {
  68572. for (var effect in this._effects) {
  68573. this._effects[effect].updateEffect();
  68574. }
  68575. };
  68576. /**
  68577. * Internal
  68578. * @returns if all the contained post processes are ready.
  68579. */
  68580. DepthOfFieldEffect.prototype._isReady = function () {
  68581. for (var effect in this._effects) {
  68582. if (!this._effects[effect].isReady()) {
  68583. return false;
  68584. }
  68585. }
  68586. return true;
  68587. };
  68588. return DepthOfFieldEffect;
  68589. }(BABYLON.PostProcessRenderEffect));
  68590. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68591. })(BABYLON || (BABYLON = {}));
  68592. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68593. var BABYLON;
  68594. (function (BABYLON) {
  68595. /**
  68596. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68597. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68598. */
  68599. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68600. __extends(DefaultRenderingPipeline, _super);
  68601. /**
  68602. * @constructor
  68603. * @param {string} name - The rendering pipeline name
  68604. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68605. * @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)
  68606. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68607. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68608. */
  68609. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68610. if (automaticBuild === void 0) { automaticBuild = true; }
  68611. var _this = _super.call(this, scene.getEngine(), name) || this;
  68612. _this._originalCameras = [];
  68613. /**
  68614. * ID of the sharpen post process,
  68615. */
  68616. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  68617. /**
  68618. * ID of the pass post process used for bloom,
  68619. */
  68620. _this.PassPostProcessId = "PassPostProcessEffect";
  68621. /**
  68622. * ID of the highlight post process used for bloom,
  68623. */
  68624. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68625. /**
  68626. * ID of the blurX post process used for bloom,
  68627. */
  68628. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68629. /**
  68630. * ID of the blurY post process used for bloom,
  68631. */
  68632. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68633. /**
  68634. * ID of the copy back post process used for bloom,
  68635. */
  68636. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68637. /**
  68638. * ID of the image processing post process;
  68639. */
  68640. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68641. /**
  68642. * ID of the Fast Approximate Anti-Aliasing post process;
  68643. */
  68644. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68645. /**
  68646. * ID of the final merge post process;
  68647. */
  68648. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68649. /**
  68650. * ID of the chromatic aberration post process,
  68651. */
  68652. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  68653. /**
  68654. * Animations which can be used to tweak settings over a period of time
  68655. */
  68656. _this.animations = [];
  68657. // Values
  68658. _this._sharpenEnabled = false;
  68659. _this._bloomEnabled = false;
  68660. _this._depthOfFieldEnabled = false;
  68661. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68662. _this._fxaaEnabled = false;
  68663. _this._msaaEnabled = false;
  68664. _this._imageProcessingEnabled = true;
  68665. _this._bloomScale = 0.6;
  68666. _this._chromaticAberrationEnabled = false;
  68667. _this._buildAllowed = true;
  68668. /**
  68669. * Specifies the size of the bloom blur kernel, relative to the final output size
  68670. */
  68671. _this.bloomKernel = 64;
  68672. /**
  68673. * Specifies the weight of the bloom in the final rendering
  68674. */
  68675. _this._bloomWeight = 0.15;
  68676. _this._prevPostProcess = null;
  68677. _this._prevPrevPostProcess = null;
  68678. _this._cameras = cameras || [];
  68679. _this._originalCameras = _this._cameras.slice();
  68680. _this._buildAllowed = automaticBuild;
  68681. // Initialize
  68682. _this._scene = scene;
  68683. var caps = _this._scene.getEngine().getCaps();
  68684. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68685. // Misc
  68686. if (_this._hdr) {
  68687. if (caps.textureHalfFloatRender) {
  68688. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68689. }
  68690. else if (caps.textureFloatRender) {
  68691. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68692. }
  68693. }
  68694. else {
  68695. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68696. }
  68697. // Attach
  68698. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68699. var engine = _this._scene.getEngine();
  68700. // Create post processes before hand so they can be modified before enabled.
  68701. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  68702. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  68703. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  68704. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  68705. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  68706. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  68707. _this._buildPipeline();
  68708. return _this;
  68709. }
  68710. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  68711. get: function () {
  68712. return this._sharpenEnabled;
  68713. },
  68714. /**
  68715. * Enable or disable the sharpen process from the pipeline
  68716. */
  68717. set: function (enabled) {
  68718. if (this._sharpenEnabled === enabled) {
  68719. return;
  68720. }
  68721. this._sharpenEnabled = enabled;
  68722. this._buildPipeline();
  68723. },
  68724. enumerable: true,
  68725. configurable: true
  68726. });
  68727. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68728. get: function () {
  68729. return this._bloomWeight;
  68730. },
  68731. /**
  68732. * The strength of the bloom.
  68733. */
  68734. set: function (value) {
  68735. if (this._bloomWeight === value) {
  68736. return;
  68737. }
  68738. this._bloomWeight = value;
  68739. if (this._hdr && this.copyBack) {
  68740. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68741. }
  68742. },
  68743. enumerable: true,
  68744. configurable: true
  68745. });
  68746. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68747. get: function () {
  68748. return this._bloomScale;
  68749. },
  68750. /**
  68751. * The scale of the bloom, lower value will provide better performance.
  68752. */
  68753. set: function (value) {
  68754. if (this._bloomScale === value) {
  68755. return;
  68756. }
  68757. this._bloomScale = value;
  68758. this._buildPipeline();
  68759. },
  68760. enumerable: true,
  68761. configurable: true
  68762. });
  68763. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68764. get: function () {
  68765. return this._bloomEnabled;
  68766. },
  68767. /**
  68768. * Enable or disable the bloom from the pipeline
  68769. */
  68770. set: function (enabled) {
  68771. if (this._bloomEnabled === enabled) {
  68772. return;
  68773. }
  68774. this._bloomEnabled = enabled;
  68775. this._buildPipeline();
  68776. },
  68777. enumerable: true,
  68778. configurable: true
  68779. });
  68780. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68781. /**
  68782. * If the depth of field is enabled.
  68783. */
  68784. get: function () {
  68785. return this._depthOfFieldEnabled;
  68786. },
  68787. set: function (enabled) {
  68788. if (this._depthOfFieldEnabled === enabled) {
  68789. return;
  68790. }
  68791. this._depthOfFieldEnabled = enabled;
  68792. this._buildPipeline();
  68793. },
  68794. enumerable: true,
  68795. configurable: true
  68796. });
  68797. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68798. /**
  68799. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68800. */
  68801. get: function () {
  68802. return this._depthOfFieldBlurLevel;
  68803. },
  68804. set: function (value) {
  68805. if (this._depthOfFieldBlurLevel === value) {
  68806. return;
  68807. }
  68808. this._depthOfFieldBlurLevel = value;
  68809. // recreate dof and dispose old as this setting is not dynamic
  68810. var oldDof = this.depthOfField;
  68811. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68812. this.depthOfField.focalLength = oldDof.focalLength;
  68813. this.depthOfField.focusDistance = oldDof.focusDistance;
  68814. this.depthOfField.fStop = oldDof.fStop;
  68815. this.depthOfField.lensSize = oldDof.lensSize;
  68816. for (var i = 0; i < this._cameras.length; i++) {
  68817. oldDof.disposeEffects(this._cameras[i]);
  68818. }
  68819. this._buildPipeline();
  68820. },
  68821. enumerable: true,
  68822. configurable: true
  68823. });
  68824. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68825. get: function () {
  68826. return this._fxaaEnabled;
  68827. },
  68828. /**
  68829. * If the anti aliasing is enabled.
  68830. */
  68831. set: function (enabled) {
  68832. if (this._fxaaEnabled === enabled) {
  68833. return;
  68834. }
  68835. this._fxaaEnabled = enabled;
  68836. this._buildPipeline();
  68837. },
  68838. enumerable: true,
  68839. configurable: true
  68840. });
  68841. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68842. get: function () {
  68843. return this._msaaEnabled;
  68844. },
  68845. /**
  68846. * If the multisample anti-aliasing is enabled.
  68847. */
  68848. set: function (enabled) {
  68849. if (this._msaaEnabled === enabled) {
  68850. return;
  68851. }
  68852. this._msaaEnabled = enabled;
  68853. this._buildPipeline();
  68854. },
  68855. enumerable: true,
  68856. configurable: true
  68857. });
  68858. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68859. get: function () {
  68860. return this._imageProcessingEnabled;
  68861. },
  68862. /**
  68863. * If image processing is enabled.
  68864. */
  68865. set: function (enabled) {
  68866. if (this._imageProcessingEnabled === enabled) {
  68867. return;
  68868. }
  68869. this._imageProcessingEnabled = enabled;
  68870. this._buildPipeline();
  68871. },
  68872. enumerable: true,
  68873. configurable: true
  68874. });
  68875. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68876. get: function () {
  68877. return this._chromaticAberrationEnabled;
  68878. },
  68879. /**
  68880. * Enable or disable the chromaticAberration process from the pipeline
  68881. */
  68882. set: function (enabled) {
  68883. if (this._chromaticAberrationEnabled === enabled) {
  68884. return;
  68885. }
  68886. this._chromaticAberrationEnabled = enabled;
  68887. this._buildPipeline();
  68888. },
  68889. enumerable: true,
  68890. configurable: true
  68891. });
  68892. /**
  68893. * Force the compilation of the entire pipeline.
  68894. */
  68895. DefaultRenderingPipeline.prototype.prepare = function () {
  68896. var previousState = this._buildAllowed;
  68897. this._buildAllowed = true;
  68898. this._buildPipeline();
  68899. this._buildAllowed = previousState;
  68900. };
  68901. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  68902. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  68903. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  68904. postProcess.autoClear = false;
  68905. }
  68906. else {
  68907. postProcess.autoClear = true;
  68908. }
  68909. if (!skipTextureSharing) {
  68910. if (this._prevPrevPostProcess) {
  68911. postProcess.shareOutputWith(this._prevPrevPostProcess);
  68912. }
  68913. else {
  68914. postProcess.useOwnOutput();
  68915. }
  68916. if (this._prevPostProcess) {
  68917. this._prevPrevPostProcess = this._prevPostProcess;
  68918. }
  68919. this._prevPostProcess = postProcess;
  68920. }
  68921. };
  68922. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68923. var _this = this;
  68924. if (!this._buildAllowed) {
  68925. return;
  68926. }
  68927. var engine = this._scene.getEngine();
  68928. this._disposePostProcesses();
  68929. if (this._cameras !== null) {
  68930. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68931. // get back cameras to be used to reattach pipeline
  68932. this._cameras = this._originalCameras.slice();
  68933. }
  68934. this._reset();
  68935. this._prevPostProcess = null;
  68936. this._prevPrevPostProcess = null;
  68937. if (this.sharpenEnabled) {
  68938. if (!this.sharpen.isReady()) {
  68939. this.sharpen.updateEffect();
  68940. }
  68941. this.addEffect(this._sharpenEffect);
  68942. this._setAutoClearAndTextureSharing(this.sharpen);
  68943. }
  68944. if (this.depthOfFieldEnabled) {
  68945. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68946. this.depthOfField.depthTexture = depthTexture;
  68947. if (!this.depthOfField._isReady()) {
  68948. this.depthOfField._updateEffects();
  68949. }
  68950. this.addEffect(this.depthOfField);
  68951. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  68952. }
  68953. if (this.bloomEnabled) {
  68954. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68955. this._setAutoClearAndTextureSharing(this.pass, true);
  68956. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68957. if (!this._hdr) {
  68958. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68959. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68960. this.highlights.autoClear = false;
  68961. this.highlights.alwaysForcePOT = true;
  68962. }
  68963. 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);
  68964. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68965. this.blurX.alwaysForcePOT = true;
  68966. this.blurX.autoClear = false;
  68967. this.blurX.onActivateObservable.add(function () {
  68968. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68969. _this.blurX.kernel = _this.bloomKernel * dw;
  68970. });
  68971. 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);
  68972. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68973. this.blurY.alwaysForcePOT = true;
  68974. this.blurY.autoClear = false;
  68975. this.blurY.onActivateObservable.add(function () {
  68976. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68977. _this.blurY.kernel = _this.bloomKernel * dh;
  68978. });
  68979. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68980. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68981. this.copyBack.alwaysForcePOT = true;
  68982. if (this._hdr) {
  68983. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68984. var w = this.bloomWeight;
  68985. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68986. }
  68987. else {
  68988. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68989. }
  68990. this.copyBack.autoClear = false;
  68991. }
  68992. if (this._imageProcessingEnabled) {
  68993. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68994. if (this._hdr) {
  68995. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68996. }
  68997. else {
  68998. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68999. }
  69000. }
  69001. if (this._hdr && this.imageProcessing) {
  69002. this.finalMerge = this.imageProcessing;
  69003. }
  69004. else {
  69005. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69006. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69007. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69008. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69009. }
  69010. if (this.bloomEnabled) {
  69011. if (this._hdr) {
  69012. this.copyBack.shareOutputWith(this.blurX);
  69013. if (this.imageProcessing) {
  69014. this.imageProcessing.shareOutputWith(this.pass);
  69015. this.imageProcessing.autoClear = false;
  69016. }
  69017. else {
  69018. this.finalMerge.shareOutputWith(this.pass);
  69019. }
  69020. }
  69021. else {
  69022. this.finalMerge.shareOutputWith(this.pass);
  69023. }
  69024. }
  69025. if (this.fxaaEnabled) {
  69026. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69027. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69028. this._setAutoClearAndTextureSharing(this.fxaa);
  69029. }
  69030. if (this.chromaticAberrationEnabled) {
  69031. if (!this.chromaticAberration.isReady()) {
  69032. this.chromaticAberration.updateEffect();
  69033. }
  69034. this.addEffect(this._chromaticAberrationEffect);
  69035. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69036. }
  69037. if (this._cameras !== null) {
  69038. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69039. }
  69040. if (this.msaaEnabled) {
  69041. if (!this._enableMSAAOnFirstPostProcess()) {
  69042. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69043. }
  69044. }
  69045. };
  69046. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69047. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69048. for (var i = 0; i < this._cameras.length; i++) {
  69049. var camera = this._cameras[i];
  69050. if (this.pass) {
  69051. this.pass.dispose(camera);
  69052. }
  69053. if (this.highlights) {
  69054. this.highlights.dispose(camera);
  69055. }
  69056. if (this.blurX) {
  69057. this.blurX.dispose(camera);
  69058. }
  69059. if (this.blurY) {
  69060. this.blurY.dispose(camera);
  69061. }
  69062. if (this.copyBack) {
  69063. this.copyBack.dispose(camera);
  69064. }
  69065. if (this.imageProcessing) {
  69066. this.imageProcessing.dispose(camera);
  69067. }
  69068. if (this.fxaa) {
  69069. this.fxaa.dispose(camera);
  69070. }
  69071. if (this.finalMerge) {
  69072. this.finalMerge.dispose(camera);
  69073. }
  69074. // These are created in the constructor and should not be disposed on every pipeline change
  69075. if (disposeNonRecreated) {
  69076. if (this.sharpen) {
  69077. this.sharpen.dispose(camera);
  69078. }
  69079. if (this.depthOfField) {
  69080. this.depthOfField.disposeEffects(camera);
  69081. }
  69082. if (this.chromaticAberration) {
  69083. this.chromaticAberration.dispose(camera);
  69084. }
  69085. }
  69086. }
  69087. this.pass = null;
  69088. this.highlights = null;
  69089. this.blurX = null;
  69090. this.blurY = null;
  69091. this.copyBack = null;
  69092. this.imageProcessing = null;
  69093. this.fxaa = null;
  69094. this.finalMerge = null;
  69095. if (disposeNonRecreated) {
  69096. this.sharpen = null;
  69097. this.depthOfField = null;
  69098. this.chromaticAberration = null;
  69099. }
  69100. };
  69101. /**
  69102. * Dispose of the pipeline and stop all post processes
  69103. */
  69104. DefaultRenderingPipeline.prototype.dispose = function () {
  69105. this._disposePostProcesses(true);
  69106. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69107. _super.prototype.dispose.call(this);
  69108. };
  69109. /**
  69110. * Serialize the rendering pipeline (Used when exporting)
  69111. * @returns the serialized object
  69112. */
  69113. DefaultRenderingPipeline.prototype.serialize = function () {
  69114. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69115. serializationObject.customType = "DefaultRenderingPipeline";
  69116. return serializationObject;
  69117. };
  69118. /**
  69119. * Parse the serialized pipeline
  69120. * @param source Source pipeline.
  69121. * @param scene The scene to load the pipeline to.
  69122. * @param rootUrl The URL of the serialized pipeline.
  69123. * @returns An instantiated pipeline from the serialized object.
  69124. */
  69125. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69126. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69127. };
  69128. __decorate([
  69129. BABYLON.serialize()
  69130. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69131. __decorate([
  69132. BABYLON.serialize()
  69133. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69134. __decorate([
  69135. BABYLON.serialize()
  69136. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69137. __decorate([
  69138. BABYLON.serialize()
  69139. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69140. __decorate([
  69141. BABYLON.serialize()
  69142. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69143. __decorate([
  69144. BABYLON.serialize()
  69145. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69146. __decorate([
  69147. BABYLON.serialize()
  69148. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69149. __decorate([
  69150. BABYLON.serialize()
  69151. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69152. __decorate([
  69153. BABYLON.serialize()
  69154. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69155. __decorate([
  69156. BABYLON.serialize()
  69157. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69158. __decorate([
  69159. BABYLON.serialize()
  69160. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69161. __decorate([
  69162. BABYLON.serialize()
  69163. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69164. __decorate([
  69165. BABYLON.serialize()
  69166. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69167. return DefaultRenderingPipeline;
  69168. }(BABYLON.PostProcessRenderPipeline));
  69169. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69170. })(BABYLON || (BABYLON = {}));
  69171. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69172. var BABYLON;
  69173. (function (BABYLON) {
  69174. /**
  69175. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69176. */
  69177. var GeometryBufferRenderer = /** @class */ (function () {
  69178. /**
  69179. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69180. * @param scene The scene the buffer belongs to
  69181. * @param ratio How big is the buffer related to the main canvas.
  69182. */
  69183. function GeometryBufferRenderer(scene, ratio) {
  69184. if (ratio === void 0) { ratio = 1; }
  69185. this._enablePosition = false;
  69186. this._scene = scene;
  69187. this._ratio = ratio;
  69188. // Render target
  69189. this._createRenderTargets();
  69190. }
  69191. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69192. /**
  69193. * Set the render list (meshes to be rendered) used in the G buffer.
  69194. */
  69195. set: function (meshes) {
  69196. this._multiRenderTarget.renderList = meshes;
  69197. },
  69198. enumerable: true,
  69199. configurable: true
  69200. });
  69201. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69202. /**
  69203. * Gets wether or not G buffer are supported by the running hardware.
  69204. * This requires draw buffer supports
  69205. */
  69206. get: function () {
  69207. return this._multiRenderTarget.isSupported;
  69208. },
  69209. enumerable: true,
  69210. configurable: true
  69211. });
  69212. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69213. /**
  69214. * Gets wether or not position are enabled for the G buffer.
  69215. */
  69216. get: function () {
  69217. return this._enablePosition;
  69218. },
  69219. /**
  69220. * Sets wether or not position are enabled for the G buffer.
  69221. */
  69222. set: function (enable) {
  69223. this._enablePosition = enable;
  69224. this.dispose();
  69225. this._createRenderTargets();
  69226. },
  69227. enumerable: true,
  69228. configurable: true
  69229. });
  69230. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69231. /**
  69232. * Gets the scene associated with the buffer.
  69233. */
  69234. get: function () {
  69235. return this._scene;
  69236. },
  69237. enumerable: true,
  69238. configurable: true
  69239. });
  69240. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69241. /**
  69242. * Gets the ratio used by the buffer during its creation.
  69243. * How big is the buffer related to the main canvas.
  69244. */
  69245. get: function () {
  69246. return this._ratio;
  69247. },
  69248. enumerable: true,
  69249. configurable: true
  69250. });
  69251. /**
  69252. * Checks wether everything is ready to render a submesh to the G buffer.
  69253. * @param subMesh the submesh to check readiness for
  69254. * @param useInstances is the mesh drawn using instance or not
  69255. * @returns true if ready otherwise false
  69256. */
  69257. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69258. var material = subMesh.getMaterial();
  69259. if (material && material.disableDepthWrite) {
  69260. return false;
  69261. }
  69262. var defines = [];
  69263. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69264. var mesh = subMesh.getMesh();
  69265. // Alpha test
  69266. if (material && material.needAlphaTesting()) {
  69267. defines.push("#define ALPHATEST");
  69268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69269. attribs.push(BABYLON.VertexBuffer.UVKind);
  69270. defines.push("#define UV1");
  69271. }
  69272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69273. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69274. defines.push("#define UV2");
  69275. }
  69276. }
  69277. // Buffers
  69278. if (this._enablePosition) {
  69279. defines.push("#define POSITION");
  69280. }
  69281. // Bones
  69282. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69285. if (mesh.numBoneInfluencers > 4) {
  69286. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69287. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69288. }
  69289. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69290. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69291. }
  69292. else {
  69293. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69294. }
  69295. // Instances
  69296. if (useInstances) {
  69297. defines.push("#define INSTANCES");
  69298. attribs.push("world0");
  69299. attribs.push("world1");
  69300. attribs.push("world2");
  69301. attribs.push("world3");
  69302. }
  69303. // Get correct effect
  69304. var join = defines.join("\n");
  69305. if (this._cachedDefines !== join) {
  69306. this._cachedDefines = join;
  69307. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69308. }
  69309. return this._effect.isReady();
  69310. };
  69311. /**
  69312. * Gets the current underlying G Buffer.
  69313. * @returns the buffer
  69314. */
  69315. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69316. return this._multiRenderTarget;
  69317. };
  69318. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69319. /**
  69320. * Gets the number of samples used to render the buffer (anti aliasing).
  69321. */
  69322. get: function () {
  69323. return this._multiRenderTarget.samples;
  69324. },
  69325. /**
  69326. * Sets the number of samples used to render the buffer (anti aliasing).
  69327. */
  69328. set: function (value) {
  69329. this._multiRenderTarget.samples = value;
  69330. },
  69331. enumerable: true,
  69332. configurable: true
  69333. });
  69334. /**
  69335. * Disposes the renderer and frees up associated resources.
  69336. */
  69337. GeometryBufferRenderer.prototype.dispose = function () {
  69338. this.getGBuffer().dispose();
  69339. };
  69340. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  69341. var _this = this;
  69342. var engine = this._scene.getEngine();
  69343. var count = this._enablePosition ? 3 : 2;
  69344. 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 });
  69345. if (!this.isSupported) {
  69346. return;
  69347. }
  69348. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69349. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69350. this._multiRenderTarget.refreshRate = 1;
  69351. this._multiRenderTarget.renderParticles = false;
  69352. this._multiRenderTarget.renderList = null;
  69353. // set default depth value to 1.0 (far away)
  69354. this._multiRenderTarget.onClearObservable.add(function (engine) {
  69355. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  69356. });
  69357. // Custom render function
  69358. var renderSubMesh = function (subMesh) {
  69359. var mesh = subMesh.getRenderingMesh();
  69360. var scene = _this._scene;
  69361. var engine = scene.getEngine();
  69362. var material = subMesh.getMaterial();
  69363. if (!material) {
  69364. return;
  69365. }
  69366. // Culling
  69367. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69368. // Managing instances
  69369. var batch = mesh._getInstancesRenderList(subMesh._id);
  69370. if (batch.mustReturn) {
  69371. return;
  69372. }
  69373. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69374. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69375. engine.enableEffect(_this._effect);
  69376. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69377. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69378. _this._effect.setMatrix("view", scene.getViewMatrix());
  69379. // Alpha test
  69380. if (material && material.needAlphaTesting()) {
  69381. var alphaTexture = material.getAlphaTestTexture();
  69382. if (alphaTexture) {
  69383. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69384. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69385. }
  69386. }
  69387. // Bones
  69388. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69389. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69390. }
  69391. // Draw
  69392. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69393. }
  69394. };
  69395. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69396. var index;
  69397. if (depthOnlySubMeshes.length) {
  69398. engine.setColorWrite(false);
  69399. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69400. renderSubMesh(depthOnlySubMeshes.data[index]);
  69401. }
  69402. engine.setColorWrite(true);
  69403. }
  69404. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69405. renderSubMesh(opaqueSubMeshes.data[index]);
  69406. }
  69407. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69408. renderSubMesh(alphaTestSubMeshes.data[index]);
  69409. }
  69410. };
  69411. };
  69412. return GeometryBufferRenderer;
  69413. }());
  69414. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69415. })(BABYLON || (BABYLON = {}));
  69416. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69417. var BABYLON;
  69418. (function (BABYLON) {
  69419. var RefractionPostProcess = /** @class */ (function (_super) {
  69420. __extends(RefractionPostProcess, _super);
  69421. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69422. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69423. _this.color = color;
  69424. _this.depth = depth;
  69425. _this.colorLevel = colorLevel;
  69426. _this._ownRefractionTexture = true;
  69427. _this.onActivateObservable.add(function (cam) {
  69428. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69429. });
  69430. _this.onApplyObservable.add(function (effect) {
  69431. effect.setColor3("baseColor", _this.color);
  69432. effect.setFloat("depth", _this.depth);
  69433. effect.setFloat("colorLevel", _this.colorLevel);
  69434. effect.setTexture("refractionSampler", _this._refTexture);
  69435. });
  69436. return _this;
  69437. }
  69438. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69439. /**
  69440. * Gets or sets the refraction texture
  69441. * Please note that you are responsible for disposing the texture if you set it manually
  69442. */
  69443. get: function () {
  69444. return this._refTexture;
  69445. },
  69446. set: function (value) {
  69447. if (this._refTexture && this._ownRefractionTexture) {
  69448. this._refTexture.dispose();
  69449. }
  69450. this._refTexture = value;
  69451. this._ownRefractionTexture = false;
  69452. },
  69453. enumerable: true,
  69454. configurable: true
  69455. });
  69456. // Methods
  69457. RefractionPostProcess.prototype.dispose = function (camera) {
  69458. if (this._refTexture && this._ownRefractionTexture) {
  69459. this._refTexture.dispose();
  69460. this._refTexture = null;
  69461. }
  69462. _super.prototype.dispose.call(this, camera);
  69463. };
  69464. return RefractionPostProcess;
  69465. }(BABYLON.PostProcess));
  69466. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69467. })(BABYLON || (BABYLON = {}));
  69468. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69469. var BABYLON;
  69470. (function (BABYLON) {
  69471. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69472. __extends(BlackAndWhitePostProcess, _super);
  69473. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69474. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69475. _this.degree = 1;
  69476. _this.onApplyObservable.add(function (effect) {
  69477. effect.setFloat("degree", _this.degree);
  69478. });
  69479. return _this;
  69480. }
  69481. return BlackAndWhitePostProcess;
  69482. }(BABYLON.PostProcess));
  69483. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69484. })(BABYLON || (BABYLON = {}));
  69485. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69486. var BABYLON;
  69487. (function (BABYLON) {
  69488. /**
  69489. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  69490. * input texture to perform effects such as edge detection or sharpening
  69491. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69492. */
  69493. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69494. __extends(ConvolutionPostProcess, _super);
  69495. /**
  69496. * Creates a new instance of @see ConvolutionPostProcess
  69497. * @param name The name of the effect.
  69498. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  69499. * @param options The required width/height ratio to downsize to before computing the render pass.
  69500. * @param camera The camera to apply the render pass to.
  69501. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69502. * @param engine The engine which the post process will be applied. (default: current engine)
  69503. * @param reusable If the post process can be reused on the same frame. (default: false)
  69504. * @param textureType Type of textures used when performing the post process. (default: 0)
  69505. */
  69506. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  69507. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69508. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69509. _this.kernel = kernel;
  69510. _this.onApply = function (effect) {
  69511. effect.setFloat2("screenSize", _this.width, _this.height);
  69512. effect.setArray("kernel", _this.kernel);
  69513. };
  69514. return _this;
  69515. }
  69516. // Statics
  69517. /**
  69518. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69519. */
  69520. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69521. /**
  69522. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69523. */
  69524. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69525. /**
  69526. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69527. */
  69528. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69529. /**
  69530. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69531. */
  69532. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69533. /**
  69534. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69535. */
  69536. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69537. /**
  69538. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69539. */
  69540. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69541. return ConvolutionPostProcess;
  69542. }(BABYLON.PostProcess));
  69543. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69544. })(BABYLON || (BABYLON = {}));
  69545. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69546. var BABYLON;
  69547. (function (BABYLON) {
  69548. var FilterPostProcess = /** @class */ (function (_super) {
  69549. __extends(FilterPostProcess, _super);
  69550. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69551. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69552. _this.kernelMatrix = kernelMatrix;
  69553. _this.onApply = function (effect) {
  69554. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69555. };
  69556. return _this;
  69557. }
  69558. return FilterPostProcess;
  69559. }(BABYLON.PostProcess));
  69560. BABYLON.FilterPostProcess = FilterPostProcess;
  69561. })(BABYLON || (BABYLON = {}));
  69562. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69563. var BABYLON;
  69564. (function (BABYLON) {
  69565. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69566. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69567. __extends(VolumetricLightScatteringPostProcess, _super);
  69568. /**
  69569. * @constructor
  69570. * @param {string} name - The post-process name
  69571. * @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)
  69572. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69573. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69574. * @param {number} samples - The post-process quality, default 100
  69575. * @param {number} samplingMode - The post-process filtering mode
  69576. * @param {BABYLON.Engine} engine - The babylon engine
  69577. * @param {boolean} reusable - If the post-process is reusable
  69578. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69579. */
  69580. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69581. if (samples === void 0) { samples = 100; }
  69582. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69583. 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;
  69584. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69585. /**
  69586. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69587. * @type {Vector3}
  69588. */
  69589. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69590. /**
  69591. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69592. * @type {boolean}
  69593. */
  69594. _this.useCustomMeshPosition = false;
  69595. /**
  69596. * If the post-process should inverse the light scattering direction
  69597. * @type {boolean}
  69598. */
  69599. _this.invert = true;
  69600. /**
  69601. * Array containing the excluded meshes not rendered in the internal pass
  69602. */
  69603. _this.excludedMeshes = new Array();
  69604. /**
  69605. * Controls the overall intensity of the post-process
  69606. * @type {number}
  69607. */
  69608. _this.exposure = 0.3;
  69609. /**
  69610. * Dissipates each sample's contribution in range [0, 1]
  69611. * @type {number}
  69612. */
  69613. _this.decay = 0.96815;
  69614. /**
  69615. * Controls the overall intensity of each sample
  69616. * @type {number}
  69617. */
  69618. _this.weight = 0.58767;
  69619. /**
  69620. * Controls the density of each sample
  69621. * @type {number}
  69622. */
  69623. _this.density = 0.926;
  69624. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69625. engine = scene.getEngine();
  69626. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69627. // Configure mesh
  69628. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69629. // Configure
  69630. _this._createPass(scene, ratio.passRatio || ratio);
  69631. _this.onActivate = function (camera) {
  69632. if (!_this.isSupported) {
  69633. _this.dispose(camera);
  69634. }
  69635. _this.onActivate = null;
  69636. };
  69637. _this.onApplyObservable.add(function (effect) {
  69638. _this._updateMeshScreenCoordinates(scene);
  69639. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69640. effect.setFloat("exposure", _this.exposure);
  69641. effect.setFloat("decay", _this.decay);
  69642. effect.setFloat("weight", _this.weight);
  69643. effect.setFloat("density", _this.density);
  69644. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69645. });
  69646. return _this;
  69647. }
  69648. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69649. get: function () {
  69650. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69651. return false;
  69652. },
  69653. set: function (useDiffuseColor) {
  69654. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69655. },
  69656. enumerable: true,
  69657. configurable: true
  69658. });
  69659. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69660. return "VolumetricLightScatteringPostProcess";
  69661. };
  69662. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69663. var mesh = subMesh.getMesh();
  69664. // Render this.mesh as default
  69665. if (mesh === this.mesh && mesh.material) {
  69666. return mesh.material.isReady(mesh);
  69667. }
  69668. var defines = [];
  69669. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69670. var material = subMesh.getMaterial();
  69671. // Alpha test
  69672. if (material) {
  69673. if (material.needAlphaTesting()) {
  69674. defines.push("#define ALPHATEST");
  69675. }
  69676. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69677. attribs.push(BABYLON.VertexBuffer.UVKind);
  69678. defines.push("#define UV1");
  69679. }
  69680. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69681. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69682. defines.push("#define UV2");
  69683. }
  69684. }
  69685. // Bones
  69686. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69687. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69688. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69689. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69690. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69691. }
  69692. else {
  69693. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69694. }
  69695. // Instances
  69696. if (useInstances) {
  69697. defines.push("#define INSTANCES");
  69698. attribs.push("world0");
  69699. attribs.push("world1");
  69700. attribs.push("world2");
  69701. attribs.push("world3");
  69702. }
  69703. // Get correct effect
  69704. var join = defines.join("\n");
  69705. if (this._cachedDefines !== join) {
  69706. this._cachedDefines = join;
  69707. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69708. }
  69709. return this._volumetricLightScatteringPass.isReady();
  69710. };
  69711. /**
  69712. * Sets the new light position for light scattering effect
  69713. * @param {BABYLON.Vector3} The new custom light position
  69714. */
  69715. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69716. this.customMeshPosition = position;
  69717. };
  69718. /**
  69719. * Returns the light position for light scattering effect
  69720. * @return {BABYLON.Vector3} The custom light position
  69721. */
  69722. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69723. return this.customMeshPosition;
  69724. };
  69725. /**
  69726. * Disposes the internal assets and detaches the post-process from the camera
  69727. */
  69728. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69729. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69730. if (rttIndex !== -1) {
  69731. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69732. }
  69733. this._volumetricLightScatteringRTT.dispose();
  69734. _super.prototype.dispose.call(this, camera);
  69735. };
  69736. /**
  69737. * Returns the render target texture used by the post-process
  69738. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69739. */
  69740. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69741. return this._volumetricLightScatteringRTT;
  69742. };
  69743. // Private methods
  69744. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69745. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69746. return true;
  69747. }
  69748. return false;
  69749. };
  69750. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69751. var _this = this;
  69752. var engine = scene.getEngine();
  69753. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69754. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69755. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69756. this._volumetricLightScatteringRTT.renderList = null;
  69757. this._volumetricLightScatteringRTT.renderParticles = false;
  69758. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69759. var camera = this.getCamera();
  69760. if (camera) {
  69761. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69762. }
  69763. else {
  69764. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69765. }
  69766. // Custom render function for submeshes
  69767. var renderSubMesh = function (subMesh) {
  69768. var mesh = subMesh.getRenderingMesh();
  69769. if (_this._meshExcluded(mesh)) {
  69770. return;
  69771. }
  69772. var material = subMesh.getMaterial();
  69773. if (!material) {
  69774. return;
  69775. }
  69776. var scene = mesh.getScene();
  69777. var engine = scene.getEngine();
  69778. // Culling
  69779. engine.setState(material.backFaceCulling);
  69780. // Managing instances
  69781. var batch = mesh._getInstancesRenderList(subMesh._id);
  69782. if (batch.mustReturn) {
  69783. return;
  69784. }
  69785. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69786. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69787. var effect = _this._volumetricLightScatteringPass;
  69788. if (mesh === _this.mesh) {
  69789. if (subMesh.effect) {
  69790. effect = subMesh.effect;
  69791. }
  69792. else {
  69793. effect = material.getEffect();
  69794. }
  69795. }
  69796. engine.enableEffect(effect);
  69797. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69798. if (mesh === _this.mesh) {
  69799. material.bind(mesh.getWorldMatrix(), mesh);
  69800. }
  69801. else {
  69802. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69803. // Alpha test
  69804. if (material && material.needAlphaTesting()) {
  69805. var alphaTexture = material.getAlphaTestTexture();
  69806. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69807. if (alphaTexture) {
  69808. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69809. }
  69810. }
  69811. // Bones
  69812. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69813. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69814. }
  69815. }
  69816. // Draw
  69817. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69818. }
  69819. };
  69820. // Render target texture callbacks
  69821. var savedSceneClearColor;
  69822. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69823. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69824. savedSceneClearColor = scene.clearColor;
  69825. scene.clearColor = sceneClearColor;
  69826. });
  69827. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69828. scene.clearColor = savedSceneClearColor;
  69829. });
  69830. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69831. var engine = scene.getEngine();
  69832. var index;
  69833. if (depthOnlySubMeshes.length) {
  69834. engine.setColorWrite(false);
  69835. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69836. renderSubMesh(depthOnlySubMeshes.data[index]);
  69837. }
  69838. engine.setColorWrite(true);
  69839. }
  69840. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69841. renderSubMesh(opaqueSubMeshes.data[index]);
  69842. }
  69843. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69844. renderSubMesh(alphaTestSubMeshes.data[index]);
  69845. }
  69846. if (transparentSubMeshes.length) {
  69847. // Sort sub meshes
  69848. for (index = 0; index < transparentSubMeshes.length; index++) {
  69849. var submesh = transparentSubMeshes.data[index];
  69850. var boundingInfo = submesh.getBoundingInfo();
  69851. if (boundingInfo && scene.activeCamera) {
  69852. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69853. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69854. }
  69855. }
  69856. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69857. sortedArray.sort(function (a, b) {
  69858. // Alpha index first
  69859. if (a._alphaIndex > b._alphaIndex) {
  69860. return 1;
  69861. }
  69862. if (a._alphaIndex < b._alphaIndex) {
  69863. return -1;
  69864. }
  69865. // Then distance to camera
  69866. if (a._distanceToCamera < b._distanceToCamera) {
  69867. return 1;
  69868. }
  69869. if (a._distanceToCamera > b._distanceToCamera) {
  69870. return -1;
  69871. }
  69872. return 0;
  69873. });
  69874. // Render sub meshes
  69875. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69876. for (index = 0; index < sortedArray.length; index++) {
  69877. renderSubMesh(sortedArray[index]);
  69878. }
  69879. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69880. }
  69881. };
  69882. };
  69883. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69884. var transform = scene.getTransformMatrix();
  69885. var meshPosition;
  69886. if (this.useCustomMeshPosition) {
  69887. meshPosition = this.customMeshPosition;
  69888. }
  69889. else if (this.attachedNode) {
  69890. meshPosition = this.attachedNode.position;
  69891. }
  69892. else {
  69893. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69894. }
  69895. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69896. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69897. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69898. if (this.invert)
  69899. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69900. };
  69901. // Static methods
  69902. /**
  69903. * Creates a default mesh for the Volumeric Light Scattering post-process
  69904. * @param {string} The mesh name
  69905. * @param {BABYLON.Scene} The scene where to create the mesh
  69906. * @return {BABYLON.Mesh} the default mesh
  69907. */
  69908. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69909. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69910. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69911. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69912. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69913. mesh.material = material;
  69914. return mesh;
  69915. };
  69916. __decorate([
  69917. BABYLON.serializeAsVector3()
  69918. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69919. __decorate([
  69920. BABYLON.serialize()
  69921. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69922. __decorate([
  69923. BABYLON.serialize()
  69924. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69925. __decorate([
  69926. BABYLON.serializeAsMeshReference()
  69927. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69928. __decorate([
  69929. BABYLON.serialize()
  69930. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69931. __decorate([
  69932. BABYLON.serialize()
  69933. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69934. __decorate([
  69935. BABYLON.serialize()
  69936. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69937. __decorate([
  69938. BABYLON.serialize()
  69939. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69940. __decorate([
  69941. BABYLON.serialize()
  69942. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69943. return VolumetricLightScatteringPostProcess;
  69944. }(BABYLON.PostProcess));
  69945. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69946. })(BABYLON || (BABYLON = {}));
  69947. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69948. //
  69949. // This post-process allows the modification of rendered colors by using
  69950. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69951. //
  69952. // The object needs to be provided an url to a texture containing the color
  69953. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69954. // Use an image editing software to tweak the LUT to match your needs.
  69955. //
  69956. // For an example of a color LUT, see here:
  69957. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69958. // For explanations on color grading, see here:
  69959. // http://udn.epicgames.com/Three/ColorGrading.html
  69960. //
  69961. var BABYLON;
  69962. (function (BABYLON) {
  69963. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69964. __extends(ColorCorrectionPostProcess, _super);
  69965. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69966. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69967. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69968. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69969. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69970. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69971. _this.onApply = function (effect) {
  69972. effect.setTexture("colorTable", _this._colorTableTexture);
  69973. };
  69974. return _this;
  69975. }
  69976. return ColorCorrectionPostProcess;
  69977. }(BABYLON.PostProcess));
  69978. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69979. })(BABYLON || (BABYLON = {}));
  69980. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69981. var BABYLON;
  69982. (function (BABYLON) {
  69983. var TonemappingOperator;
  69984. (function (TonemappingOperator) {
  69985. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69986. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69987. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69988. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69989. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69990. ;
  69991. var TonemapPostProcess = /** @class */ (function (_super) {
  69992. __extends(TonemapPostProcess, _super);
  69993. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69995. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69996. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69997. _this._operator = _operator;
  69998. _this.exposureAdjustment = exposureAdjustment;
  69999. var defines = "#define ";
  70000. if (_this._operator === TonemappingOperator.Hable)
  70001. defines += "HABLE_TONEMAPPING";
  70002. else if (_this._operator === TonemappingOperator.Reinhard)
  70003. defines += "REINHARD_TONEMAPPING";
  70004. else if (_this._operator === TonemappingOperator.HejiDawson)
  70005. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70006. else if (_this._operator === TonemappingOperator.Photographic)
  70007. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70008. //sadly a second call to create the effect.
  70009. _this.updateEffect(defines);
  70010. _this.onApply = function (effect) {
  70011. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70012. };
  70013. return _this;
  70014. }
  70015. return TonemapPostProcess;
  70016. }(BABYLON.PostProcess));
  70017. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70018. })(BABYLON || (BABYLON = {}));
  70019. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70020. var BABYLON;
  70021. (function (BABYLON) {
  70022. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70023. __extends(DisplayPassPostProcess, _super);
  70024. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70025. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70026. }
  70027. return DisplayPassPostProcess;
  70028. }(BABYLON.PostProcess));
  70029. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70030. })(BABYLON || (BABYLON = {}));
  70031. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70032. var BABYLON;
  70033. (function (BABYLON) {
  70034. var HighlightsPostProcess = /** @class */ (function (_super) {
  70035. __extends(HighlightsPostProcess, _super);
  70036. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70037. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70038. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70039. }
  70040. return HighlightsPostProcess;
  70041. }(BABYLON.PostProcess));
  70042. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70043. })(BABYLON || (BABYLON = {}));
  70044. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70045. var BABYLON;
  70046. (function (BABYLON) {
  70047. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70048. __extends(ImageProcessingPostProcess, _super);
  70049. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70050. if (camera === void 0) { camera = null; }
  70051. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70052. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70053. _this._fromLinearSpace = true;
  70054. /**
  70055. * Defines cache preventing GC.
  70056. */
  70057. _this._defines = {
  70058. IMAGEPROCESSING: false,
  70059. VIGNETTE: false,
  70060. VIGNETTEBLENDMODEMULTIPLY: false,
  70061. VIGNETTEBLENDMODEOPAQUE: false,
  70062. TONEMAPPING: false,
  70063. CONTRAST: false,
  70064. COLORCURVES: false,
  70065. COLORGRADING: false,
  70066. COLORGRADING3D: false,
  70067. FROMLINEARSPACE: false,
  70068. SAMPLER3DGREENDEPTH: false,
  70069. SAMPLER3DBGRMAP: false,
  70070. IMAGEPROCESSINGPOSTPROCESS: false,
  70071. EXPOSURE: false,
  70072. GRAIN: false,
  70073. };
  70074. // Setup the configuration as forced by the constructor. This would then not force the
  70075. // scene materials output in linear space and let untouched the default forward pass.
  70076. if (imageProcessingConfiguration) {
  70077. imageProcessingConfiguration.applyByPostProcess = true;
  70078. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70079. // This will cause the shader to be compiled
  70080. _this.fromLinearSpace = false;
  70081. }
  70082. else {
  70083. _this._attachImageProcessingConfiguration(null, true);
  70084. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70085. }
  70086. _this.onApply = function (effect) {
  70087. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70088. };
  70089. return _this;
  70090. }
  70091. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70092. /**
  70093. * Gets the image processing configuration used either in this material.
  70094. */
  70095. get: function () {
  70096. return this._imageProcessingConfiguration;
  70097. },
  70098. /**
  70099. * Sets the Default image processing configuration used either in the this material.
  70100. *
  70101. * If sets to null, the scene one is in use.
  70102. */
  70103. set: function (value) {
  70104. this._attachImageProcessingConfiguration(value);
  70105. },
  70106. enumerable: true,
  70107. configurable: true
  70108. });
  70109. /**
  70110. * Attaches a new image processing configuration to the PBR Material.
  70111. * @param configuration
  70112. */
  70113. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70114. var _this = this;
  70115. if (doNotBuild === void 0) { doNotBuild = false; }
  70116. if (configuration === this._imageProcessingConfiguration) {
  70117. return;
  70118. }
  70119. // Detaches observer.
  70120. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70121. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70122. }
  70123. // Pick the scene configuration if needed.
  70124. if (!configuration) {
  70125. var scene = null;
  70126. var engine = this.getEngine();
  70127. var camera = this.getCamera();
  70128. if (camera) {
  70129. scene = camera.getScene();
  70130. }
  70131. else if (engine && engine.scenes) {
  70132. var scenes = engine.scenes;
  70133. scene = scenes[scenes.length - 1];
  70134. }
  70135. else {
  70136. scene = BABYLON.Engine.LastCreatedScene;
  70137. }
  70138. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70139. }
  70140. else {
  70141. this._imageProcessingConfiguration = configuration;
  70142. }
  70143. // Attaches observer.
  70144. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70145. _this._updateParameters();
  70146. });
  70147. // Ensure the effect will be rebuilt.
  70148. if (!doNotBuild) {
  70149. this._updateParameters();
  70150. }
  70151. };
  70152. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70153. /**
  70154. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70155. */
  70156. get: function () {
  70157. return this.imageProcessingConfiguration.colorCurves;
  70158. },
  70159. /**
  70160. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70161. */
  70162. set: function (value) {
  70163. this.imageProcessingConfiguration.colorCurves = value;
  70164. },
  70165. enumerable: true,
  70166. configurable: true
  70167. });
  70168. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70169. /**
  70170. * Gets wether the color curves effect is enabled.
  70171. */
  70172. get: function () {
  70173. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70174. },
  70175. /**
  70176. * Sets wether the color curves effect is enabled.
  70177. */
  70178. set: function (value) {
  70179. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70180. },
  70181. enumerable: true,
  70182. configurable: true
  70183. });
  70184. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70185. /**
  70186. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70187. */
  70188. get: function () {
  70189. return this.imageProcessingConfiguration.colorGradingTexture;
  70190. },
  70191. /**
  70192. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70193. */
  70194. set: function (value) {
  70195. this.imageProcessingConfiguration.colorGradingTexture = value;
  70196. },
  70197. enumerable: true,
  70198. configurable: true
  70199. });
  70200. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70201. /**
  70202. * Gets wether the color grading effect is enabled.
  70203. */
  70204. get: function () {
  70205. return this.imageProcessingConfiguration.colorGradingEnabled;
  70206. },
  70207. /**
  70208. * Gets wether the color grading effect is enabled.
  70209. */
  70210. set: function (value) {
  70211. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70212. },
  70213. enumerable: true,
  70214. configurable: true
  70215. });
  70216. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70217. /**
  70218. * Gets exposure used in the effect.
  70219. */
  70220. get: function () {
  70221. return this.imageProcessingConfiguration.exposure;
  70222. },
  70223. /**
  70224. * Sets exposure used in the effect.
  70225. */
  70226. set: function (value) {
  70227. this.imageProcessingConfiguration.exposure = value;
  70228. },
  70229. enumerable: true,
  70230. configurable: true
  70231. });
  70232. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70233. /**
  70234. * Gets wether tonemapping is enabled or not.
  70235. */
  70236. get: function () {
  70237. return this._imageProcessingConfiguration.toneMappingEnabled;
  70238. },
  70239. /**
  70240. * Sets wether tonemapping is enabled or not
  70241. */
  70242. set: function (value) {
  70243. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70244. },
  70245. enumerable: true,
  70246. configurable: true
  70247. });
  70248. ;
  70249. ;
  70250. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70251. /**
  70252. * Gets contrast used in the effect.
  70253. */
  70254. get: function () {
  70255. return this.imageProcessingConfiguration.contrast;
  70256. },
  70257. /**
  70258. * Sets contrast used in the effect.
  70259. */
  70260. set: function (value) {
  70261. this.imageProcessingConfiguration.contrast = value;
  70262. },
  70263. enumerable: true,
  70264. configurable: true
  70265. });
  70266. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70267. /**
  70268. * Gets Vignette stretch size.
  70269. */
  70270. get: function () {
  70271. return this.imageProcessingConfiguration.vignetteStretch;
  70272. },
  70273. /**
  70274. * Sets Vignette stretch size.
  70275. */
  70276. set: function (value) {
  70277. this.imageProcessingConfiguration.vignetteStretch = value;
  70278. },
  70279. enumerable: true,
  70280. configurable: true
  70281. });
  70282. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70283. /**
  70284. * Gets Vignette centre X Offset.
  70285. */
  70286. get: function () {
  70287. return this.imageProcessingConfiguration.vignetteCentreX;
  70288. },
  70289. /**
  70290. * Sets Vignette centre X Offset.
  70291. */
  70292. set: function (value) {
  70293. this.imageProcessingConfiguration.vignetteCentreX = value;
  70294. },
  70295. enumerable: true,
  70296. configurable: true
  70297. });
  70298. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70299. /**
  70300. * Gets Vignette centre Y Offset.
  70301. */
  70302. get: function () {
  70303. return this.imageProcessingConfiguration.vignetteCentreY;
  70304. },
  70305. /**
  70306. * Sets Vignette centre Y Offset.
  70307. */
  70308. set: function (value) {
  70309. this.imageProcessingConfiguration.vignetteCentreY = value;
  70310. },
  70311. enumerable: true,
  70312. configurable: true
  70313. });
  70314. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70315. /**
  70316. * Gets Vignette weight or intensity of the vignette effect.
  70317. */
  70318. get: function () {
  70319. return this.imageProcessingConfiguration.vignetteWeight;
  70320. },
  70321. /**
  70322. * Sets Vignette weight or intensity of the vignette effect.
  70323. */
  70324. set: function (value) {
  70325. this.imageProcessingConfiguration.vignetteWeight = value;
  70326. },
  70327. enumerable: true,
  70328. configurable: true
  70329. });
  70330. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  70331. /**
  70332. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70333. * if vignetteEnabled is set to true.
  70334. */
  70335. get: function () {
  70336. return this.imageProcessingConfiguration.vignetteColor;
  70337. },
  70338. /**
  70339. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70340. * if vignetteEnabled is set to true.
  70341. */
  70342. set: function (value) {
  70343. this.imageProcessingConfiguration.vignetteColor = value;
  70344. },
  70345. enumerable: true,
  70346. configurable: true
  70347. });
  70348. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  70349. /**
  70350. * Gets Camera field of view used by the Vignette effect.
  70351. */
  70352. get: function () {
  70353. return this.imageProcessingConfiguration.vignetteCameraFov;
  70354. },
  70355. /**
  70356. * Sets Camera field of view used by the Vignette effect.
  70357. */
  70358. set: function (value) {
  70359. this.imageProcessingConfiguration.vignetteCameraFov = value;
  70360. },
  70361. enumerable: true,
  70362. configurable: true
  70363. });
  70364. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  70365. /**
  70366. * Gets the vignette blend mode allowing different kind of effect.
  70367. */
  70368. get: function () {
  70369. return this.imageProcessingConfiguration.vignetteBlendMode;
  70370. },
  70371. /**
  70372. * Sets the vignette blend mode allowing different kind of effect.
  70373. */
  70374. set: function (value) {
  70375. this.imageProcessingConfiguration.vignetteBlendMode = value;
  70376. },
  70377. enumerable: true,
  70378. configurable: true
  70379. });
  70380. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  70381. /**
  70382. * Gets wether the vignette effect is enabled.
  70383. */
  70384. get: function () {
  70385. return this.imageProcessingConfiguration.vignetteEnabled;
  70386. },
  70387. /**
  70388. * Sets wether the vignette effect is enabled.
  70389. */
  70390. set: function (value) {
  70391. this.imageProcessingConfiguration.vignetteEnabled = value;
  70392. },
  70393. enumerable: true,
  70394. configurable: true
  70395. });
  70396. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  70397. /**
  70398. * Gets wether the grain effect is enabled.
  70399. */
  70400. get: function () {
  70401. return this.imageProcessingConfiguration.grainEnabled;
  70402. },
  70403. /**
  70404. * Sets wether the grain effect is enabled.
  70405. */
  70406. set: function (value) {
  70407. this.imageProcessingConfiguration.grainEnabled = value;
  70408. },
  70409. enumerable: true,
  70410. configurable: true
  70411. });
  70412. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  70413. /**
  70414. * Gets the grain effect's intensity.
  70415. */
  70416. get: function () {
  70417. return this.imageProcessingConfiguration.grainIntensity;
  70418. },
  70419. /**
  70420. * Sets the grain effect's intensity.
  70421. */
  70422. set: function (value) {
  70423. this.imageProcessingConfiguration.grainIntensity = value;
  70424. },
  70425. enumerable: true,
  70426. configurable: true
  70427. });
  70428. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  70429. /**
  70430. * Gets wether the grain effect is animated.
  70431. */
  70432. get: function () {
  70433. return this.imageProcessingConfiguration.grainAnimated;
  70434. },
  70435. /**
  70436. * Sets wether the grain effect is animated.
  70437. */
  70438. set: function (value) {
  70439. this.imageProcessingConfiguration.grainAnimated = value;
  70440. },
  70441. enumerable: true,
  70442. configurable: true
  70443. });
  70444. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  70445. /**
  70446. * Gets wether the input of the processing is in Gamma or Linear Space.
  70447. */
  70448. get: function () {
  70449. return this._fromLinearSpace;
  70450. },
  70451. /**
  70452. * Sets wether the input of the processing is in Gamma or Linear Space.
  70453. */
  70454. set: function (value) {
  70455. if (this._fromLinearSpace === value) {
  70456. return;
  70457. }
  70458. this._fromLinearSpace = value;
  70459. this._updateParameters();
  70460. },
  70461. enumerable: true,
  70462. configurable: true
  70463. });
  70464. ImageProcessingPostProcess.prototype.getClassName = function () {
  70465. return "ImageProcessingPostProcess";
  70466. };
  70467. ImageProcessingPostProcess.prototype._updateParameters = function () {
  70468. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  70469. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  70470. var defines = "";
  70471. for (var define in this._defines) {
  70472. if (this._defines[define]) {
  70473. defines += "#define " + define + ";\r\n";
  70474. }
  70475. }
  70476. var samplers = ["textureSampler"];
  70477. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  70478. var uniforms = ["scale"];
  70479. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  70480. this.updateEffect(defines, uniforms, samplers);
  70481. };
  70482. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  70483. _super.prototype.dispose.call(this, camera);
  70484. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70485. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70486. }
  70487. this.imageProcessingConfiguration.applyByPostProcess = false;
  70488. };
  70489. __decorate([
  70490. BABYLON.serialize()
  70491. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70492. return ImageProcessingPostProcess;
  70493. }(BABYLON.PostProcess));
  70494. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70495. })(BABYLON || (BABYLON = {}));
  70496. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70497. var BABYLON;
  70498. (function (BABYLON) {
  70499. var Bone = /** @class */ (function (_super) {
  70500. __extends(Bone, _super);
  70501. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70502. if (parentBone === void 0) { parentBone = null; }
  70503. if (localMatrix === void 0) { localMatrix = null; }
  70504. if (restPose === void 0) { restPose = null; }
  70505. if (baseMatrix === void 0) { baseMatrix = null; }
  70506. if (index === void 0) { index = null; }
  70507. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70508. _this.name = name;
  70509. _this.children = new Array();
  70510. _this.animations = new Array();
  70511. // Set this value to map this bone to a different index in the transform matrices.
  70512. // Set this value to -1 to exclude the bone from the transform matrices.
  70513. _this._index = null;
  70514. _this._worldTransform = new BABYLON.Matrix();
  70515. _this._absoluteTransform = new BABYLON.Matrix();
  70516. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70517. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70518. _this._scaleVector = BABYLON.Vector3.One();
  70519. _this._negateScaleChildren = BABYLON.Vector3.One();
  70520. _this._scalingDeterminant = 1;
  70521. _this._skeleton = skeleton;
  70522. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70523. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70524. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70525. _this._index = index;
  70526. skeleton.bones.push(_this);
  70527. _this.setParent(parentBone, false);
  70528. _this._updateDifferenceMatrix();
  70529. return _this;
  70530. }
  70531. Object.defineProperty(Bone.prototype, "_matrix", {
  70532. get: function () {
  70533. return this._localMatrix;
  70534. },
  70535. set: function (val) {
  70536. if (this._localMatrix) {
  70537. this._localMatrix.copyFrom(val);
  70538. }
  70539. else {
  70540. this._localMatrix = val;
  70541. }
  70542. },
  70543. enumerable: true,
  70544. configurable: true
  70545. });
  70546. // Members
  70547. Bone.prototype.getSkeleton = function () {
  70548. return this._skeleton;
  70549. };
  70550. Bone.prototype.getParent = function () {
  70551. return this._parent;
  70552. };
  70553. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70554. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70555. if (this._parent === parent) {
  70556. return;
  70557. }
  70558. if (this._parent) {
  70559. var index = this._parent.children.indexOf(this);
  70560. if (index !== -1) {
  70561. this._parent.children.splice(index, 1);
  70562. }
  70563. }
  70564. this._parent = parent;
  70565. if (this._parent) {
  70566. this._parent.children.push(this);
  70567. }
  70568. if (updateDifferenceMatrix) {
  70569. this._updateDifferenceMatrix();
  70570. }
  70571. };
  70572. Bone.prototype.getLocalMatrix = function () {
  70573. return this._localMatrix;
  70574. };
  70575. Bone.prototype.getBaseMatrix = function () {
  70576. return this._baseMatrix;
  70577. };
  70578. Bone.prototype.getRestPose = function () {
  70579. return this._restPose;
  70580. };
  70581. Bone.prototype.returnToRest = function () {
  70582. this.updateMatrix(this._restPose.clone());
  70583. };
  70584. Bone.prototype.getWorldMatrix = function () {
  70585. return this._worldTransform;
  70586. };
  70587. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70588. return this._invertedAbsoluteTransform;
  70589. };
  70590. Bone.prototype.getAbsoluteTransform = function () {
  70591. return this._absoluteTransform;
  70592. };
  70593. Object.defineProperty(Bone.prototype, "position", {
  70594. // Properties (matches AbstractMesh properties)
  70595. get: function () {
  70596. return this.getPosition();
  70597. },
  70598. set: function (newPosition) {
  70599. this.setPosition(newPosition);
  70600. },
  70601. enumerable: true,
  70602. configurable: true
  70603. });
  70604. Object.defineProperty(Bone.prototype, "rotation", {
  70605. get: function () {
  70606. return this.getRotation();
  70607. },
  70608. set: function (newRotation) {
  70609. this.setRotation(newRotation);
  70610. },
  70611. enumerable: true,
  70612. configurable: true
  70613. });
  70614. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70615. get: function () {
  70616. return this.getRotationQuaternion();
  70617. },
  70618. set: function (newRotation) {
  70619. this.setRotationQuaternion(newRotation);
  70620. },
  70621. enumerable: true,
  70622. configurable: true
  70623. });
  70624. Object.defineProperty(Bone.prototype, "scaling", {
  70625. get: function () {
  70626. return this.getScale();
  70627. },
  70628. set: function (newScaling) {
  70629. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70630. },
  70631. enumerable: true,
  70632. configurable: true
  70633. });
  70634. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70635. /**
  70636. * Gets the animation properties override
  70637. */
  70638. get: function () {
  70639. return this._skeleton.animationPropertiesOverride;
  70640. },
  70641. enumerable: true,
  70642. configurable: true
  70643. });
  70644. // Methods
  70645. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70646. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70647. this._baseMatrix = matrix.clone();
  70648. this._localMatrix = matrix.clone();
  70649. this._skeleton._markAsDirty();
  70650. if (updateDifferenceMatrix) {
  70651. this._updateDifferenceMatrix();
  70652. }
  70653. };
  70654. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70655. if (!rootMatrix) {
  70656. rootMatrix = this._baseMatrix;
  70657. }
  70658. if (this._parent) {
  70659. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70660. }
  70661. else {
  70662. this._absoluteTransform.copyFrom(rootMatrix);
  70663. }
  70664. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70665. for (var index = 0; index < this.children.length; index++) {
  70666. this.children[index]._updateDifferenceMatrix();
  70667. }
  70668. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70669. };
  70670. Bone.prototype.markAsDirty = function () {
  70671. this._currentRenderId++;
  70672. this._skeleton._markAsDirty();
  70673. };
  70674. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70675. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70676. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70677. // all animation may be coming from a library skeleton, so may need to create animation
  70678. if (this.animations.length === 0) {
  70679. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70680. this.animations[0].setKeys([]);
  70681. }
  70682. // get animation info / verify there is such a range from the source bone
  70683. var sourceRange = source.animations[0].getRange(rangeName);
  70684. if (!sourceRange) {
  70685. return false;
  70686. }
  70687. var from = sourceRange.from;
  70688. var to = sourceRange.to;
  70689. var sourceKeys = source.animations[0].getKeys();
  70690. // rescaling prep
  70691. var sourceBoneLength = source.length;
  70692. var sourceParent = source.getParent();
  70693. var parent = this.getParent();
  70694. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70695. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70696. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70697. var destKeys = this.animations[0].getKeys();
  70698. // loop vars declaration
  70699. var orig;
  70700. var origTranslation;
  70701. var mat;
  70702. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70703. orig = sourceKeys[key];
  70704. if (orig.frame >= from && orig.frame <= to) {
  70705. if (rescaleAsRequired) {
  70706. mat = orig.value.clone();
  70707. // scale based on parent ratio, when bone has parent
  70708. if (parentScalingReqd) {
  70709. origTranslation = mat.getTranslation();
  70710. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70711. // scale based on skeleton dimension ratio when root bone, and value is passed
  70712. }
  70713. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70714. origTranslation = mat.getTranslation();
  70715. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70716. // use original when root bone, and no data for skelDimensionsRatio
  70717. }
  70718. else {
  70719. mat = orig.value;
  70720. }
  70721. }
  70722. else {
  70723. mat = orig.value;
  70724. }
  70725. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70726. }
  70727. }
  70728. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70729. return true;
  70730. };
  70731. /**
  70732. * Translate the bone in local or world space.
  70733. * @param vec The amount to translate the bone.
  70734. * @param space The space that the translation is in.
  70735. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70736. */
  70737. Bone.prototype.translate = function (vec, space, mesh) {
  70738. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70739. var lm = this.getLocalMatrix();
  70740. if (space == BABYLON.Space.LOCAL) {
  70741. lm.m[12] += vec.x;
  70742. lm.m[13] += vec.y;
  70743. lm.m[14] += vec.z;
  70744. }
  70745. else {
  70746. var wm = null;
  70747. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70748. if (mesh) {
  70749. wm = mesh.getWorldMatrix();
  70750. }
  70751. this._skeleton.computeAbsoluteTransforms();
  70752. var tmat = Bone._tmpMats[0];
  70753. var tvec = Bone._tmpVecs[0];
  70754. if (this._parent) {
  70755. if (mesh && wm) {
  70756. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70757. tmat.multiplyToRef(wm, tmat);
  70758. }
  70759. else {
  70760. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70761. }
  70762. }
  70763. tmat.m[12] = 0;
  70764. tmat.m[13] = 0;
  70765. tmat.m[14] = 0;
  70766. tmat.invert();
  70767. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70768. lm.m[12] += tvec.x;
  70769. lm.m[13] += tvec.y;
  70770. lm.m[14] += tvec.z;
  70771. }
  70772. this.markAsDirty();
  70773. };
  70774. /**
  70775. * Set the postion of the bone in local or world space.
  70776. * @param position The position to set the bone.
  70777. * @param space The space that the position is in.
  70778. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70779. */
  70780. Bone.prototype.setPosition = function (position, space, mesh) {
  70781. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70782. var lm = this.getLocalMatrix();
  70783. if (space == BABYLON.Space.LOCAL) {
  70784. lm.m[12] = position.x;
  70785. lm.m[13] = position.y;
  70786. lm.m[14] = position.z;
  70787. }
  70788. else {
  70789. var wm = null;
  70790. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70791. if (mesh) {
  70792. wm = mesh.getWorldMatrix();
  70793. }
  70794. this._skeleton.computeAbsoluteTransforms();
  70795. var tmat = Bone._tmpMats[0];
  70796. var vec = Bone._tmpVecs[0];
  70797. if (this._parent) {
  70798. if (mesh && wm) {
  70799. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70800. tmat.multiplyToRef(wm, tmat);
  70801. }
  70802. else {
  70803. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70804. }
  70805. }
  70806. tmat.invert();
  70807. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70808. lm.m[12] = vec.x;
  70809. lm.m[13] = vec.y;
  70810. lm.m[14] = vec.z;
  70811. }
  70812. this.markAsDirty();
  70813. };
  70814. /**
  70815. * Set the absolute postion of the bone (world space).
  70816. * @param position The position to set the bone.
  70817. * @param mesh The mesh that this bone is attached to.
  70818. */
  70819. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70820. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70821. };
  70822. /**
  70823. * Set the scale of the bone on the x, y and z axes.
  70824. * @param x The scale of the bone on the x axis.
  70825. * @param x The scale of the bone on the y axis.
  70826. * @param z The scale of the bone on the z axis.
  70827. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70828. */
  70829. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70830. if (scaleChildren === void 0) { scaleChildren = false; }
  70831. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70832. if (!scaleChildren) {
  70833. this._negateScaleChildren.x = 1 / x;
  70834. this._negateScaleChildren.y = 1 / y;
  70835. this._negateScaleChildren.z = 1 / z;
  70836. }
  70837. this._syncScaleVector();
  70838. }
  70839. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70840. };
  70841. /**
  70842. * Scale the bone on the x, y and z axes.
  70843. * @param x The amount to scale the bone on the x axis.
  70844. * @param x The amount to scale the bone on the y axis.
  70845. * @param z The amount to scale the bone on the z axis.
  70846. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70847. */
  70848. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70849. if (scaleChildren === void 0) { scaleChildren = false; }
  70850. var locMat = this.getLocalMatrix();
  70851. var origLocMat = Bone._tmpMats[0];
  70852. origLocMat.copyFrom(locMat);
  70853. var origLocMatInv = Bone._tmpMats[1];
  70854. origLocMatInv.copyFrom(origLocMat);
  70855. origLocMatInv.invert();
  70856. var scaleMat = Bone._tmpMats[2];
  70857. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70858. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70859. this._scaleVector.x *= x;
  70860. this._scaleVector.y *= y;
  70861. this._scaleVector.z *= z;
  70862. locMat.multiplyToRef(origLocMatInv, locMat);
  70863. locMat.multiplyToRef(scaleMat, locMat);
  70864. locMat.multiplyToRef(origLocMat, locMat);
  70865. var parent = this.getParent();
  70866. if (parent) {
  70867. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70868. }
  70869. else {
  70870. this.getAbsoluteTransform().copyFrom(locMat);
  70871. }
  70872. var len = this.children.length;
  70873. scaleMat.invert();
  70874. for (var i = 0; i < len; i++) {
  70875. var child = this.children[i];
  70876. var cm = child.getLocalMatrix();
  70877. cm.multiplyToRef(scaleMat, cm);
  70878. var lm = child.getLocalMatrix();
  70879. lm.m[12] *= x;
  70880. lm.m[13] *= y;
  70881. lm.m[14] *= z;
  70882. }
  70883. this.computeAbsoluteTransforms();
  70884. if (scaleChildren) {
  70885. for (var i = 0; i < len; i++) {
  70886. this.children[i].scale(x, y, z, scaleChildren);
  70887. }
  70888. }
  70889. this.markAsDirty();
  70890. };
  70891. /**
  70892. * Set the yaw, pitch, and roll of the bone in local or world space.
  70893. * @param yaw The rotation of the bone on the y axis.
  70894. * @param pitch The rotation of the bone on the x axis.
  70895. * @param roll The rotation of the bone on the z axis.
  70896. * @param space The space that the axes of rotation are in.
  70897. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70898. */
  70899. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70901. var rotMat = Bone._tmpMats[0];
  70902. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70903. var rotMatInv = Bone._tmpMats[1];
  70904. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70905. rotMatInv.multiplyToRef(rotMat, rotMat);
  70906. this._rotateWithMatrix(rotMat, space, mesh);
  70907. };
  70908. /**
  70909. * Rotate the bone on an axis in local or world space.
  70910. * @param axis The axis to rotate the bone on.
  70911. * @param amount The amount to rotate the bone.
  70912. * @param space The space that the axis is in.
  70913. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70914. */
  70915. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70916. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70917. var rmat = Bone._tmpMats[0];
  70918. rmat.m[12] = 0;
  70919. rmat.m[13] = 0;
  70920. rmat.m[14] = 0;
  70921. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70922. this._rotateWithMatrix(rmat, space, mesh);
  70923. };
  70924. /**
  70925. * Set the rotation of the bone to a particular axis angle in local or world space.
  70926. * @param axis The axis to rotate the bone on.
  70927. * @param angle The angle that the bone should be rotated to.
  70928. * @param space The space that the axis is in.
  70929. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70930. */
  70931. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70933. var rotMat = Bone._tmpMats[0];
  70934. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70935. var rotMatInv = Bone._tmpMats[1];
  70936. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70937. rotMatInv.multiplyToRef(rotMat, rotMat);
  70938. this._rotateWithMatrix(rotMat, space, mesh);
  70939. };
  70940. /**
  70941. * Set the euler rotation of the bone in local of world space.
  70942. * @param rotation The euler rotation that the bone should be set to.
  70943. * @param space The space that the rotation is in.
  70944. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70945. */
  70946. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70947. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70948. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70949. };
  70950. /**
  70951. * Set the quaternion rotation of the bone in local of world space.
  70952. * @param quat The quaternion rotation that the bone should be set to.
  70953. * @param space The space that the rotation is in.
  70954. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70955. */
  70956. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70957. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70958. var rotMatInv = Bone._tmpMats[0];
  70959. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70960. var rotMat = Bone._tmpMats[1];
  70961. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70962. rotMatInv.multiplyToRef(rotMat, rotMat);
  70963. this._rotateWithMatrix(rotMat, space, mesh);
  70964. };
  70965. /**
  70966. * Set the rotation matrix of the bone in local of world space.
  70967. * @param rotMat The rotation matrix that the bone should be set to.
  70968. * @param space The space that the rotation is in.
  70969. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70970. */
  70971. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70972. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70973. var rotMatInv = Bone._tmpMats[0];
  70974. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70975. var rotMat2 = Bone._tmpMats[1];
  70976. rotMat2.copyFrom(rotMat);
  70977. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70978. this._rotateWithMatrix(rotMat2, space, mesh);
  70979. };
  70980. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70981. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70982. var lmat = this.getLocalMatrix();
  70983. var lx = lmat.m[12];
  70984. var ly = lmat.m[13];
  70985. var lz = lmat.m[14];
  70986. var parent = this.getParent();
  70987. var parentScale = Bone._tmpMats[3];
  70988. var parentScaleInv = Bone._tmpMats[4];
  70989. if (parent) {
  70990. if (space == BABYLON.Space.WORLD) {
  70991. if (mesh) {
  70992. parentScale.copyFrom(mesh.getWorldMatrix());
  70993. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70994. }
  70995. else {
  70996. parentScale.copyFrom(parent.getAbsoluteTransform());
  70997. }
  70998. }
  70999. else {
  71000. parentScale = parent._scaleMatrix;
  71001. }
  71002. parentScaleInv.copyFrom(parentScale);
  71003. parentScaleInv.invert();
  71004. lmat.multiplyToRef(parentScale, lmat);
  71005. lmat.multiplyToRef(rmat, lmat);
  71006. lmat.multiplyToRef(parentScaleInv, lmat);
  71007. }
  71008. else {
  71009. if (space == BABYLON.Space.WORLD && mesh) {
  71010. parentScale.copyFrom(mesh.getWorldMatrix());
  71011. parentScaleInv.copyFrom(parentScale);
  71012. parentScaleInv.invert();
  71013. lmat.multiplyToRef(parentScale, lmat);
  71014. lmat.multiplyToRef(rmat, lmat);
  71015. lmat.multiplyToRef(parentScaleInv, lmat);
  71016. }
  71017. else {
  71018. lmat.multiplyToRef(rmat, lmat);
  71019. }
  71020. }
  71021. lmat.m[12] = lx;
  71022. lmat.m[13] = ly;
  71023. lmat.m[14] = lz;
  71024. this.computeAbsoluteTransforms();
  71025. this.markAsDirty();
  71026. };
  71027. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71028. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71029. if (space == BABYLON.Space.WORLD) {
  71030. var scaleMatrix = Bone._tmpMats[2];
  71031. scaleMatrix.copyFrom(this._scaleMatrix);
  71032. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71033. if (mesh) {
  71034. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71035. var meshScale = Bone._tmpMats[3];
  71036. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71037. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71038. }
  71039. rotMatInv.invert();
  71040. scaleMatrix.m[0] *= this._scalingDeterminant;
  71041. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71042. }
  71043. else {
  71044. rotMatInv.copyFrom(this.getLocalMatrix());
  71045. rotMatInv.invert();
  71046. var scaleMatrix = Bone._tmpMats[2];
  71047. scaleMatrix.copyFrom(this._scaleMatrix);
  71048. if (this._parent) {
  71049. var pscaleMatrix = Bone._tmpMats[3];
  71050. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71051. pscaleMatrix.invert();
  71052. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71053. }
  71054. else {
  71055. scaleMatrix.m[0] *= this._scalingDeterminant;
  71056. }
  71057. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71058. }
  71059. };
  71060. /**
  71061. * Get the scale of the bone
  71062. * @returns the scale of the bone
  71063. */
  71064. Bone.prototype.getScale = function () {
  71065. return this._scaleVector.clone();
  71066. };
  71067. /**
  71068. * Copy the scale of the bone to a vector3.
  71069. * @param result The vector3 to copy the scale to
  71070. */
  71071. Bone.prototype.getScaleToRef = function (result) {
  71072. result.copyFrom(this._scaleVector);
  71073. };
  71074. /**
  71075. * Get the position of the bone in local or world space.
  71076. * @param space The space that the returned position is in.
  71077. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71078. * @returns The position of the bone
  71079. */
  71080. Bone.prototype.getPosition = function (space, mesh) {
  71081. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71082. if (mesh === void 0) { mesh = null; }
  71083. var pos = BABYLON.Vector3.Zero();
  71084. this.getPositionToRef(space, mesh, pos);
  71085. return pos;
  71086. };
  71087. /**
  71088. * Copy the position of the bone to a vector3 in local or world space.
  71089. * @param space The space that the returned position is in.
  71090. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71091. * @param result The vector3 to copy the position to.
  71092. */
  71093. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71094. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71095. if (space == BABYLON.Space.LOCAL) {
  71096. var lm = this.getLocalMatrix();
  71097. result.x = lm.m[12];
  71098. result.y = lm.m[13];
  71099. result.z = lm.m[14];
  71100. }
  71101. else {
  71102. var wm = null;
  71103. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71104. if (mesh) {
  71105. wm = mesh.getWorldMatrix();
  71106. }
  71107. this._skeleton.computeAbsoluteTransforms();
  71108. var tmat = Bone._tmpMats[0];
  71109. if (mesh && wm) {
  71110. tmat.copyFrom(this.getAbsoluteTransform());
  71111. tmat.multiplyToRef(wm, tmat);
  71112. }
  71113. else {
  71114. tmat = this.getAbsoluteTransform();
  71115. }
  71116. result.x = tmat.m[12];
  71117. result.y = tmat.m[13];
  71118. result.z = tmat.m[14];
  71119. }
  71120. };
  71121. /**
  71122. * Get the absolute position of the bone (world space).
  71123. * @param mesh The mesh that this bone is attached to.
  71124. * @returns The absolute position of the bone
  71125. */
  71126. Bone.prototype.getAbsolutePosition = function (mesh) {
  71127. if (mesh === void 0) { mesh = null; }
  71128. var pos = BABYLON.Vector3.Zero();
  71129. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71130. return pos;
  71131. };
  71132. /**
  71133. * Copy the absolute position of the bone (world space) to the result param.
  71134. * @param mesh The mesh that this bone is attached to.
  71135. * @param result The vector3 to copy the absolute position to.
  71136. */
  71137. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71138. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71139. };
  71140. /**
  71141. * Compute the absolute transforms of this bone and its children.
  71142. */
  71143. Bone.prototype.computeAbsoluteTransforms = function () {
  71144. if (this._parent) {
  71145. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71146. }
  71147. else {
  71148. this._absoluteTransform.copyFrom(this._localMatrix);
  71149. var poseMatrix = this._skeleton.getPoseMatrix();
  71150. if (poseMatrix) {
  71151. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71152. }
  71153. }
  71154. var children = this.children;
  71155. var len = children.length;
  71156. for (var i = 0; i < len; i++) {
  71157. children[i].computeAbsoluteTransforms();
  71158. }
  71159. };
  71160. Bone.prototype._syncScaleVector = function () {
  71161. var lm = this.getLocalMatrix();
  71162. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71163. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71164. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71165. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71166. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71167. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71168. this._scaleVector.x = xs * Math.sqrt(xsq);
  71169. this._scaleVector.y = ys * Math.sqrt(ysq);
  71170. this._scaleVector.z = zs * Math.sqrt(zsq);
  71171. if (this._parent) {
  71172. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71173. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71174. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71175. }
  71176. 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);
  71177. };
  71178. /**
  71179. * Get the world direction from an axis that is in the local space of the bone.
  71180. * @param localAxis The local direction that is used to compute the world direction.
  71181. * @param mesh The mesh that this bone is attached to.
  71182. * @returns The world direction
  71183. */
  71184. Bone.prototype.getDirection = function (localAxis, mesh) {
  71185. if (mesh === void 0) { mesh = null; }
  71186. var result = BABYLON.Vector3.Zero();
  71187. this.getDirectionToRef(localAxis, mesh, result);
  71188. return result;
  71189. };
  71190. /**
  71191. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71192. * @param localAxis The local direction that is used to compute the world direction.
  71193. * @param mesh The mesh that this bone is attached to.
  71194. * @param result The vector3 that the world direction will be copied to.
  71195. */
  71196. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71197. if (mesh === void 0) { mesh = null; }
  71198. var wm = null;
  71199. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71200. if (mesh) {
  71201. wm = mesh.getWorldMatrix();
  71202. }
  71203. this._skeleton.computeAbsoluteTransforms();
  71204. var mat = Bone._tmpMats[0];
  71205. mat.copyFrom(this.getAbsoluteTransform());
  71206. if (mesh && wm) {
  71207. mat.multiplyToRef(wm, mat);
  71208. }
  71209. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71210. result.normalize();
  71211. };
  71212. /**
  71213. * Get the euler rotation of the bone in local or world space.
  71214. * @param space The space that the rotation should be in.
  71215. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71216. * @returns The euler rotation
  71217. */
  71218. Bone.prototype.getRotation = function (space, mesh) {
  71219. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71220. if (mesh === void 0) { mesh = null; }
  71221. var result = BABYLON.Vector3.Zero();
  71222. this.getRotationToRef(space, mesh, result);
  71223. return result;
  71224. };
  71225. /**
  71226. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71227. * @param space The space that the rotation should be in.
  71228. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71229. * @param result The vector3 that the rotation should be copied to.
  71230. */
  71231. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71232. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71233. if (mesh === void 0) { mesh = null; }
  71234. var quat = Bone._tmpQuat;
  71235. this.getRotationQuaternionToRef(space, mesh, quat);
  71236. quat.toEulerAnglesToRef(result);
  71237. };
  71238. /**
  71239. * Get the quaternion rotation of the bone in either local or world space.
  71240. * @param space The space that the rotation should be in.
  71241. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71242. * @returns The quaternion rotation
  71243. */
  71244. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71245. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71246. if (mesh === void 0) { mesh = null; }
  71247. var result = BABYLON.Quaternion.Identity();
  71248. this.getRotationQuaternionToRef(space, mesh, result);
  71249. return result;
  71250. };
  71251. /**
  71252. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71253. * @param space The space that the rotation should be in.
  71254. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71255. * @param result The quaternion that the rotation should be copied to.
  71256. */
  71257. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71258. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71259. if (mesh === void 0) { mesh = null; }
  71260. if (space == BABYLON.Space.LOCAL) {
  71261. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71262. }
  71263. else {
  71264. var mat = Bone._tmpMats[0];
  71265. var amat = this.getAbsoluteTransform();
  71266. if (mesh) {
  71267. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71268. }
  71269. else {
  71270. mat.copyFrom(amat);
  71271. }
  71272. mat.m[0] *= this._scalingDeterminant;
  71273. mat.m[1] *= this._scalingDeterminant;
  71274. mat.m[2] *= this._scalingDeterminant;
  71275. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71276. }
  71277. };
  71278. /**
  71279. * Get the rotation matrix of the bone in local or world space.
  71280. * @param space The space that the rotation should be in.
  71281. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71282. * @returns The rotation matrix
  71283. */
  71284. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71285. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71286. var result = BABYLON.Matrix.Identity();
  71287. this.getRotationMatrixToRef(space, mesh, result);
  71288. return result;
  71289. };
  71290. /**
  71291. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71292. * @param space The space that the rotation should be in.
  71293. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71294. * @param result The quaternion that the rotation should be copied to.
  71295. */
  71296. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71297. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71298. if (space == BABYLON.Space.LOCAL) {
  71299. this.getLocalMatrix().getRotationMatrixToRef(result);
  71300. }
  71301. else {
  71302. var mat = Bone._tmpMats[0];
  71303. var amat = this.getAbsoluteTransform();
  71304. if (mesh) {
  71305. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71306. }
  71307. else {
  71308. mat.copyFrom(amat);
  71309. }
  71310. mat.m[0] *= this._scalingDeterminant;
  71311. mat.m[1] *= this._scalingDeterminant;
  71312. mat.m[2] *= this._scalingDeterminant;
  71313. mat.getRotationMatrixToRef(result);
  71314. }
  71315. };
  71316. /**
  71317. * Get the world position of a point that is in the local space of the bone.
  71318. * @param position The local position
  71319. * @param mesh The mesh that this bone is attached to.
  71320. * @returns The world position
  71321. */
  71322. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71323. if (mesh === void 0) { mesh = null; }
  71324. var result = BABYLON.Vector3.Zero();
  71325. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71326. return result;
  71327. };
  71328. /**
  71329. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71330. * @param position The local position
  71331. * @param mesh The mesh that this bone is attached to.
  71332. * @param result The vector3 that the world position should be copied to.
  71333. */
  71334. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71335. if (mesh === void 0) { mesh = null; }
  71336. var wm = null;
  71337. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71338. if (mesh) {
  71339. wm = mesh.getWorldMatrix();
  71340. }
  71341. this._skeleton.computeAbsoluteTransforms();
  71342. var tmat = Bone._tmpMats[0];
  71343. if (mesh && wm) {
  71344. tmat.copyFrom(this.getAbsoluteTransform());
  71345. tmat.multiplyToRef(wm, tmat);
  71346. }
  71347. else {
  71348. tmat = this.getAbsoluteTransform();
  71349. }
  71350. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71351. };
  71352. /**
  71353. * Get the local position of a point that is in world space.
  71354. * @param position The world position
  71355. * @param mesh The mesh that this bone is attached to.
  71356. * @returns The local position
  71357. */
  71358. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71359. if (mesh === void 0) { mesh = null; }
  71360. var result = BABYLON.Vector3.Zero();
  71361. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71362. return result;
  71363. };
  71364. /**
  71365. * Get the local position of a point that is in world space and copy it to the result param.
  71366. * @param position The world position
  71367. * @param mesh The mesh that this bone is attached to.
  71368. * @param result The vector3 that the local position should be copied to.
  71369. */
  71370. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71371. if (mesh === void 0) { mesh = null; }
  71372. var wm = null;
  71373. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71374. if (mesh) {
  71375. wm = mesh.getWorldMatrix();
  71376. }
  71377. this._skeleton.computeAbsoluteTransforms();
  71378. var tmat = Bone._tmpMats[0];
  71379. tmat.copyFrom(this.getAbsoluteTransform());
  71380. if (mesh && wm) {
  71381. tmat.multiplyToRef(wm, tmat);
  71382. }
  71383. tmat.invert();
  71384. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71385. };
  71386. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71387. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71388. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71389. return Bone;
  71390. }(BABYLON.Node));
  71391. BABYLON.Bone = Bone;
  71392. })(BABYLON || (BABYLON = {}));
  71393. //# sourceMappingURL=babylon.bone.js.map
  71394. var BABYLON;
  71395. (function (BABYLON) {
  71396. var BoneIKController = /** @class */ (function () {
  71397. function BoneIKController(mesh, bone, options) {
  71398. this.targetPosition = BABYLON.Vector3.Zero();
  71399. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71400. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71401. this.poleAngle = 0;
  71402. this.slerpAmount = 1;
  71403. this._bone1Quat = BABYLON.Quaternion.Identity();
  71404. this._bone1Mat = BABYLON.Matrix.Identity();
  71405. this._bone2Ang = Math.PI;
  71406. this._maxAngle = Math.PI;
  71407. this._rightHandedSystem = false;
  71408. this._bendAxis = BABYLON.Vector3.Right();
  71409. this._slerping = false;
  71410. this._adjustRoll = 0;
  71411. this._bone2 = bone;
  71412. this._bone1 = bone.getParent();
  71413. if (!this._bone1) {
  71414. return;
  71415. }
  71416. this.mesh = mesh;
  71417. var bonePos = bone.getPosition();
  71418. if (bone.getAbsoluteTransform().determinant() > 0) {
  71419. this._rightHandedSystem = true;
  71420. this._bendAxis.x = 0;
  71421. this._bendAxis.y = 0;
  71422. this._bendAxis.z = -1;
  71423. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71424. this._adjustRoll = Math.PI * .5;
  71425. this._bendAxis.z = 1;
  71426. }
  71427. }
  71428. if (this._bone1.length) {
  71429. var boneScale1 = this._bone1.getScale();
  71430. var boneScale2 = this._bone2.getScale();
  71431. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71432. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71433. }
  71434. else if (this._bone1.children[0]) {
  71435. mesh.computeWorldMatrix(true);
  71436. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71437. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71438. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71439. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71440. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71441. }
  71442. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71443. this.maxAngle = Math.PI;
  71444. if (options) {
  71445. if (options.targetMesh) {
  71446. this.targetMesh = options.targetMesh;
  71447. this.targetMesh.computeWorldMatrix(true);
  71448. }
  71449. if (options.poleTargetMesh) {
  71450. this.poleTargetMesh = options.poleTargetMesh;
  71451. this.poleTargetMesh.computeWorldMatrix(true);
  71452. }
  71453. else if (options.poleTargetBone) {
  71454. this.poleTargetBone = options.poleTargetBone;
  71455. }
  71456. else if (this._bone1.getParent()) {
  71457. this.poleTargetBone = this._bone1.getParent();
  71458. }
  71459. if (options.poleTargetLocalOffset) {
  71460. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71461. }
  71462. if (options.poleAngle) {
  71463. this.poleAngle = options.poleAngle;
  71464. }
  71465. if (options.bendAxis) {
  71466. this._bendAxis.copyFrom(options.bendAxis);
  71467. }
  71468. if (options.maxAngle) {
  71469. this.maxAngle = options.maxAngle;
  71470. }
  71471. if (options.slerpAmount) {
  71472. this.slerpAmount = options.slerpAmount;
  71473. }
  71474. }
  71475. }
  71476. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71477. get: function () {
  71478. return this._maxAngle;
  71479. },
  71480. set: function (value) {
  71481. this._setMaxAngle(value);
  71482. },
  71483. enumerable: true,
  71484. configurable: true
  71485. });
  71486. BoneIKController.prototype._setMaxAngle = function (ang) {
  71487. if (ang < 0) {
  71488. ang = 0;
  71489. }
  71490. if (ang > Math.PI || ang == undefined) {
  71491. ang = Math.PI;
  71492. }
  71493. this._maxAngle = ang;
  71494. var a = this._bone1Length;
  71495. var b = this._bone2Length;
  71496. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71497. };
  71498. BoneIKController.prototype.update = function () {
  71499. var bone1 = this._bone1;
  71500. if (!bone1) {
  71501. return;
  71502. }
  71503. var target = this.targetPosition;
  71504. var poleTarget = this.poleTargetPosition;
  71505. var mat1 = BoneIKController._tmpMats[0];
  71506. var mat2 = BoneIKController._tmpMats[1];
  71507. if (this.targetMesh) {
  71508. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71509. }
  71510. if (this.poleTargetBone) {
  71511. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71512. }
  71513. else if (this.poleTargetMesh) {
  71514. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71515. }
  71516. var bonePos = BoneIKController._tmpVecs[0];
  71517. var zaxis = BoneIKController._tmpVecs[1];
  71518. var xaxis = BoneIKController._tmpVecs[2];
  71519. var yaxis = BoneIKController._tmpVecs[3];
  71520. var upAxis = BoneIKController._tmpVecs[4];
  71521. var _tmpQuat = BoneIKController._tmpQuat;
  71522. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71523. poleTarget.subtractToRef(bonePos, upAxis);
  71524. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71525. upAxis.y = 1;
  71526. }
  71527. else {
  71528. upAxis.normalize();
  71529. }
  71530. target.subtractToRef(bonePos, yaxis);
  71531. yaxis.normalize();
  71532. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71533. zaxis.normalize();
  71534. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71535. xaxis.normalize();
  71536. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71537. var a = this._bone1Length;
  71538. var b = this._bone2Length;
  71539. var c = BABYLON.Vector3.Distance(bonePos, target);
  71540. if (this._maxReach > 0) {
  71541. c = Math.min(this._maxReach, c);
  71542. }
  71543. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71544. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71545. if (acosa > 1) {
  71546. acosa = 1;
  71547. }
  71548. if (acosb > 1) {
  71549. acosb = 1;
  71550. }
  71551. if (acosa < -1) {
  71552. acosa = -1;
  71553. }
  71554. if (acosb < -1) {
  71555. acosb = -1;
  71556. }
  71557. var angA = Math.acos(acosa);
  71558. var angB = Math.acos(acosb);
  71559. var angC = -angA - angB;
  71560. if (this._rightHandedSystem) {
  71561. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71562. mat2.multiplyToRef(mat1, mat1);
  71563. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71564. mat2.multiplyToRef(mat1, mat1);
  71565. }
  71566. else {
  71567. var _tmpVec = BoneIKController._tmpVecs[5];
  71568. _tmpVec.copyFrom(this._bendAxis);
  71569. _tmpVec.x *= -1;
  71570. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71571. mat2.multiplyToRef(mat1, mat1);
  71572. }
  71573. if (this.poleAngle) {
  71574. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71575. mat1.multiplyToRef(mat2, mat1);
  71576. }
  71577. if (this._bone1) {
  71578. if (this.slerpAmount < 1) {
  71579. if (!this._slerping) {
  71580. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71581. }
  71582. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71583. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71584. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71585. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71586. this._slerping = true;
  71587. }
  71588. else {
  71589. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71590. this._bone1Mat.copyFrom(mat1);
  71591. this._slerping = false;
  71592. }
  71593. }
  71594. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71595. this._bone2Ang = angC;
  71596. };
  71597. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71598. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71599. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71600. return BoneIKController;
  71601. }());
  71602. BABYLON.BoneIKController = BoneIKController;
  71603. })(BABYLON || (BABYLON = {}));
  71604. //# sourceMappingURL=babylon.boneIKController.js.map
  71605. var BABYLON;
  71606. (function (BABYLON) {
  71607. var BoneLookController = /** @class */ (function () {
  71608. /**
  71609. * Create a BoneLookController
  71610. * @param mesh the mesh that the bone belongs to
  71611. * @param bone the bone that will be looking to the target
  71612. * @param target the target Vector3 to look at
  71613. * @param settings optional settings:
  71614. * - maxYaw: the maximum angle the bone will yaw to
  71615. * - minYaw: the minimum angle the bone will yaw to
  71616. * - maxPitch: the maximum angle the bone will pitch to
  71617. * - minPitch: the minimum angle the bone will yaw to
  71618. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71619. * - upAxis: the up axis of the coordinate system
  71620. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71621. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71622. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71623. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71624. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71625. * - adjustRoll: used to make an adjustment to the roll of the bone
  71626. **/
  71627. function BoneLookController(mesh, bone, target, options) {
  71628. /**
  71629. * The up axis of the coordinate system that is used when the bone is rotated.
  71630. */
  71631. this.upAxis = BABYLON.Vector3.Up();
  71632. /**
  71633. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71634. */
  71635. this.upAxisSpace = BABYLON.Space.LOCAL;
  71636. /**
  71637. * Used to make an adjustment to the yaw of the bone.
  71638. */
  71639. this.adjustYaw = 0;
  71640. /**
  71641. * Used to make an adjustment to the pitch of the bone.
  71642. */
  71643. this.adjustPitch = 0;
  71644. /**
  71645. * Used to make an adjustment to the roll of the bone.
  71646. */
  71647. this.adjustRoll = 0;
  71648. /**
  71649. * 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).
  71650. */
  71651. this.slerpAmount = 1;
  71652. this._boneQuat = BABYLON.Quaternion.Identity();
  71653. this._slerping = false;
  71654. this._firstFrameSkipped = false;
  71655. this._fowardAxis = BABYLON.Vector3.Forward();
  71656. this.mesh = mesh;
  71657. this.bone = bone;
  71658. this.target = target;
  71659. if (options) {
  71660. if (options.adjustYaw) {
  71661. this.adjustYaw = options.adjustYaw;
  71662. }
  71663. if (options.adjustPitch) {
  71664. this.adjustPitch = options.adjustPitch;
  71665. }
  71666. if (options.adjustRoll) {
  71667. this.adjustRoll = options.adjustRoll;
  71668. }
  71669. if (options.maxYaw != null) {
  71670. this.maxYaw = options.maxYaw;
  71671. }
  71672. else {
  71673. this.maxYaw = Math.PI;
  71674. }
  71675. if (options.minYaw != null) {
  71676. this.minYaw = options.minYaw;
  71677. }
  71678. else {
  71679. this.minYaw = -Math.PI;
  71680. }
  71681. if (options.maxPitch != null) {
  71682. this.maxPitch = options.maxPitch;
  71683. }
  71684. else {
  71685. this.maxPitch = Math.PI;
  71686. }
  71687. if (options.minPitch != null) {
  71688. this.minPitch = options.minPitch;
  71689. }
  71690. else {
  71691. this.minPitch = -Math.PI;
  71692. }
  71693. if (options.slerpAmount != null) {
  71694. this.slerpAmount = options.slerpAmount;
  71695. }
  71696. if (options.upAxis != null) {
  71697. this.upAxis = options.upAxis;
  71698. }
  71699. if (options.upAxisSpace != null) {
  71700. this.upAxisSpace = options.upAxisSpace;
  71701. }
  71702. if (options.yawAxis != null || options.pitchAxis != null) {
  71703. var newYawAxis = BABYLON.Axis.Y;
  71704. var newPitchAxis = BABYLON.Axis.X;
  71705. if (options.yawAxis != null) {
  71706. newYawAxis = options.yawAxis.clone();
  71707. newYawAxis.normalize();
  71708. }
  71709. if (options.pitchAxis != null) {
  71710. newPitchAxis = options.pitchAxis.clone();
  71711. newPitchAxis.normalize();
  71712. }
  71713. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71714. this._transformYawPitch = BABYLON.Matrix.Identity();
  71715. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71716. this._transformYawPitchInv = this._transformYawPitch.clone();
  71717. this._transformYawPitch.invert();
  71718. }
  71719. }
  71720. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71721. this.upAxisSpace = BABYLON.Space.LOCAL;
  71722. }
  71723. }
  71724. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71725. /**
  71726. * Get/set the minimum yaw angle that the bone can look to.
  71727. */
  71728. get: function () {
  71729. return this._minYaw;
  71730. },
  71731. set: function (value) {
  71732. this._minYaw = value;
  71733. this._minYawSin = Math.sin(value);
  71734. this._minYawCos = Math.cos(value);
  71735. if (this._maxYaw != null) {
  71736. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71737. this._yawRange = this._maxYaw - this._minYaw;
  71738. }
  71739. },
  71740. enumerable: true,
  71741. configurable: true
  71742. });
  71743. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71744. /**
  71745. * Get/set the maximum yaw angle that the bone can look to.
  71746. */
  71747. get: function () {
  71748. return this._maxYaw;
  71749. },
  71750. set: function (value) {
  71751. this._maxYaw = value;
  71752. this._maxYawSin = Math.sin(value);
  71753. this._maxYawCos = Math.cos(value);
  71754. if (this._minYaw != null) {
  71755. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71756. this._yawRange = this._maxYaw - this._minYaw;
  71757. }
  71758. },
  71759. enumerable: true,
  71760. configurable: true
  71761. });
  71762. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71763. /**
  71764. * Get/set the minimum pitch angle that the bone can look to.
  71765. */
  71766. get: function () {
  71767. return this._minPitch;
  71768. },
  71769. set: function (value) {
  71770. this._minPitch = value;
  71771. this._minPitchTan = Math.tan(value);
  71772. },
  71773. enumerable: true,
  71774. configurable: true
  71775. });
  71776. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71777. /**
  71778. * Get/set the maximum pitch angle that the bone can look to.
  71779. */
  71780. get: function () {
  71781. return this._maxPitch;
  71782. },
  71783. set: function (value) {
  71784. this._maxPitch = value;
  71785. this._maxPitchTan = Math.tan(value);
  71786. },
  71787. enumerable: true,
  71788. configurable: true
  71789. });
  71790. /**
  71791. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71792. */
  71793. BoneLookController.prototype.update = function () {
  71794. //skip the first frame when slerping so that the mesh rotation is correct
  71795. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71796. this._firstFrameSkipped = true;
  71797. return;
  71798. }
  71799. var bone = this.bone;
  71800. var bonePos = BoneLookController._tmpVecs[0];
  71801. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71802. var target = this.target;
  71803. var _tmpMat1 = BoneLookController._tmpMats[0];
  71804. var _tmpMat2 = BoneLookController._tmpMats[1];
  71805. var mesh = this.mesh;
  71806. var parentBone = bone.getParent();
  71807. var upAxis = BoneLookController._tmpVecs[1];
  71808. upAxis.copyFrom(this.upAxis);
  71809. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71810. if (this._transformYawPitch) {
  71811. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71812. }
  71813. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71814. }
  71815. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71816. mesh.getDirectionToRef(upAxis, upAxis);
  71817. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71818. upAxis.normalize();
  71819. }
  71820. }
  71821. var checkYaw = false;
  71822. var checkPitch = false;
  71823. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71824. checkYaw = true;
  71825. }
  71826. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71827. checkPitch = true;
  71828. }
  71829. if (checkYaw || checkPitch) {
  71830. var spaceMat = BoneLookController._tmpMats[2];
  71831. var spaceMatInv = BoneLookController._tmpMats[3];
  71832. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71833. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71834. }
  71835. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71836. spaceMat.copyFrom(mesh.getWorldMatrix());
  71837. }
  71838. else {
  71839. var forwardAxis = BoneLookController._tmpVecs[2];
  71840. forwardAxis.copyFrom(this._fowardAxis);
  71841. if (this._transformYawPitch) {
  71842. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71843. }
  71844. if (parentBone) {
  71845. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71846. }
  71847. else {
  71848. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71849. }
  71850. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71851. rightAxis.normalize();
  71852. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71853. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71854. }
  71855. spaceMat.invertToRef(spaceMatInv);
  71856. var xzlen = null;
  71857. if (checkPitch) {
  71858. var localTarget = BoneLookController._tmpVecs[3];
  71859. target.subtractToRef(bonePos, localTarget);
  71860. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71861. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71862. var pitch = Math.atan2(localTarget.y, xzlen);
  71863. var newPitch = pitch;
  71864. if (pitch > this._maxPitch) {
  71865. localTarget.y = this._maxPitchTan * xzlen;
  71866. newPitch = this._maxPitch;
  71867. }
  71868. else if (pitch < this._minPitch) {
  71869. localTarget.y = this._minPitchTan * xzlen;
  71870. newPitch = this._minPitch;
  71871. }
  71872. if (pitch != newPitch) {
  71873. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71874. localTarget.addInPlace(bonePos);
  71875. target = localTarget;
  71876. }
  71877. }
  71878. if (checkYaw) {
  71879. var localTarget = BoneLookController._tmpVecs[4];
  71880. target.subtractToRef(bonePos, localTarget);
  71881. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71882. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71883. var newYaw = yaw;
  71884. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71885. if (xzlen == null) {
  71886. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71887. }
  71888. if (this._yawRange > Math.PI) {
  71889. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71890. localTarget.z = this._maxYawCos * xzlen;
  71891. localTarget.x = this._maxYawSin * xzlen;
  71892. newYaw = this._maxYaw;
  71893. }
  71894. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71895. localTarget.z = this._minYawCos * xzlen;
  71896. localTarget.x = this._minYawSin * xzlen;
  71897. newYaw = this._minYaw;
  71898. }
  71899. }
  71900. else {
  71901. if (yaw > this._maxYaw) {
  71902. localTarget.z = this._maxYawCos * xzlen;
  71903. localTarget.x = this._maxYawSin * xzlen;
  71904. newYaw = this._maxYaw;
  71905. }
  71906. else if (yaw < this._minYaw) {
  71907. localTarget.z = this._minYawCos * xzlen;
  71908. localTarget.x = this._minYawSin * xzlen;
  71909. newYaw = this._minYaw;
  71910. }
  71911. }
  71912. }
  71913. if (this._slerping && this._yawRange > Math.PI) {
  71914. //are we going to be crossing into the min/max region?
  71915. var boneFwd = BoneLookController._tmpVecs[8];
  71916. boneFwd.copyFrom(BABYLON.Axis.Z);
  71917. if (this._transformYawPitch) {
  71918. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71919. }
  71920. var boneRotMat = BoneLookController._tmpMats[4];
  71921. this._boneQuat.toRotationMatrix(boneRotMat);
  71922. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71923. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71924. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71925. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71926. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71927. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71928. if (angBtwTar > angBtwMidYaw) {
  71929. if (xzlen == null) {
  71930. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71931. }
  71932. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71933. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71934. if (angBtwMin < angBtwMax) {
  71935. newYaw = boneYaw + Math.PI * .75;
  71936. localTarget.z = Math.cos(newYaw) * xzlen;
  71937. localTarget.x = Math.sin(newYaw) * xzlen;
  71938. }
  71939. else {
  71940. newYaw = boneYaw - Math.PI * .75;
  71941. localTarget.z = Math.cos(newYaw) * xzlen;
  71942. localTarget.x = Math.sin(newYaw) * xzlen;
  71943. }
  71944. }
  71945. }
  71946. if (yaw != newYaw) {
  71947. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71948. localTarget.addInPlace(bonePos);
  71949. target = localTarget;
  71950. }
  71951. }
  71952. }
  71953. var zaxis = BoneLookController._tmpVecs[5];
  71954. var xaxis = BoneLookController._tmpVecs[6];
  71955. var yaxis = BoneLookController._tmpVecs[7];
  71956. var _tmpQuat = BoneLookController._tmpQuat;
  71957. target.subtractToRef(bonePos, zaxis);
  71958. zaxis.normalize();
  71959. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71960. xaxis.normalize();
  71961. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71962. yaxis.normalize();
  71963. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71964. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71965. return;
  71966. }
  71967. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71968. return;
  71969. }
  71970. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71971. return;
  71972. }
  71973. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71974. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71975. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71976. }
  71977. if (this.slerpAmount < 1) {
  71978. if (!this._slerping) {
  71979. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71980. }
  71981. if (this._transformYawPitch) {
  71982. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71983. }
  71984. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71985. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71986. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71987. this._slerping = true;
  71988. }
  71989. else {
  71990. if (this._transformYawPitch) {
  71991. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71992. }
  71993. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71994. this._slerping = false;
  71995. }
  71996. };
  71997. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71998. var angDiff = ang2 - ang1;
  71999. angDiff %= Math.PI * 2;
  72000. if (angDiff > Math.PI) {
  72001. angDiff -= Math.PI * 2;
  72002. }
  72003. else if (angDiff < -Math.PI) {
  72004. angDiff += Math.PI * 2;
  72005. }
  72006. return angDiff;
  72007. };
  72008. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72009. ang1 %= (2 * Math.PI);
  72010. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72011. ang2 %= (2 * Math.PI);
  72012. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72013. var ab = 0;
  72014. if (ang1 < ang2) {
  72015. ab = ang2 - ang1;
  72016. }
  72017. else {
  72018. ab = ang1 - ang2;
  72019. }
  72020. if (ab > Math.PI) {
  72021. ab = Math.PI * 2 - ab;
  72022. }
  72023. return ab;
  72024. };
  72025. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72026. ang %= (2 * Math.PI);
  72027. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72028. ang1 %= (2 * Math.PI);
  72029. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72030. ang2 %= (2 * Math.PI);
  72031. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72032. if (ang1 < ang2) {
  72033. if (ang > ang1 && ang < ang2) {
  72034. return true;
  72035. }
  72036. }
  72037. else {
  72038. if (ang > ang2 && ang < ang1) {
  72039. return true;
  72040. }
  72041. }
  72042. return false;
  72043. };
  72044. 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()];
  72045. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72046. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72047. return BoneLookController;
  72048. }());
  72049. BABYLON.BoneLookController = BoneLookController;
  72050. })(BABYLON || (BABYLON = {}));
  72051. //# sourceMappingURL=babylon.boneLookController.js.map
  72052. var BABYLON;
  72053. (function (BABYLON) {
  72054. var Skeleton = /** @class */ (function () {
  72055. function Skeleton(name, id, scene) {
  72056. this.name = name;
  72057. this.id = id;
  72058. this.bones = new Array();
  72059. this.needInitialSkinMatrix = false;
  72060. this._isDirty = true;
  72061. this._meshesWithPoseMatrix = new Array();
  72062. this._identity = BABYLON.Matrix.Identity();
  72063. this._ranges = {};
  72064. this._lastAbsoluteTransformsUpdateId = -1;
  72065. /**
  72066. * Specifies if the skeleton should be serialized.
  72067. */
  72068. this.doNotSerialize = false;
  72069. // Events
  72070. /**
  72071. * An event triggered before computing the skeleton's matrices
  72072. * @type {BABYLON.Observable}
  72073. */
  72074. this.onBeforeComputeObservable = new BABYLON.Observable();
  72075. this.bones = [];
  72076. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72077. scene.skeletons.push(this);
  72078. //make sure it will recalculate the matrix next time prepare is called.
  72079. this._isDirty = true;
  72080. }
  72081. // Members
  72082. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72083. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72084. return mesh._bonesTransformMatrices;
  72085. }
  72086. if (!this._transformMatrices) {
  72087. this.prepare();
  72088. }
  72089. return this._transformMatrices;
  72090. };
  72091. Skeleton.prototype.getScene = function () {
  72092. return this._scene;
  72093. };
  72094. // Methods
  72095. /**
  72096. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72097. */
  72098. Skeleton.prototype.toString = function (fullDetails) {
  72099. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72100. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72101. if (fullDetails) {
  72102. ret += ", Ranges: {";
  72103. var first = true;
  72104. for (var name_1 in this._ranges) {
  72105. if (first) {
  72106. ret += ", ";
  72107. first = false;
  72108. }
  72109. ret += name_1;
  72110. }
  72111. ret += "}";
  72112. }
  72113. return ret;
  72114. };
  72115. /**
  72116. * Get bone's index searching by name
  72117. * @param {string} name is bone's name to search for
  72118. * @return {number} Indice of the bone. Returns -1 if not found
  72119. */
  72120. Skeleton.prototype.getBoneIndexByName = function (name) {
  72121. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72122. if (this.bones[boneIndex].name === name) {
  72123. return boneIndex;
  72124. }
  72125. }
  72126. return -1;
  72127. };
  72128. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72129. // check name not already in use
  72130. if (!this._ranges[name]) {
  72131. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72132. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72133. if (this.bones[i].animations[0]) {
  72134. this.bones[i].animations[0].createRange(name, from, to);
  72135. }
  72136. }
  72137. }
  72138. };
  72139. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72140. if (deleteFrames === void 0) { deleteFrames = true; }
  72141. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72142. if (this.bones[i].animations[0]) {
  72143. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72144. }
  72145. }
  72146. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72147. };
  72148. Skeleton.prototype.getAnimationRange = function (name) {
  72149. return this._ranges[name];
  72150. };
  72151. /**
  72152. * Returns as an Array, all AnimationRanges defined on this skeleton
  72153. */
  72154. Skeleton.prototype.getAnimationRanges = function () {
  72155. var animationRanges = [];
  72156. var name;
  72157. var i = 0;
  72158. for (name in this._ranges) {
  72159. animationRanges[i] = this._ranges[name];
  72160. i++;
  72161. }
  72162. return animationRanges;
  72163. };
  72164. /**
  72165. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72166. */
  72167. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72168. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72169. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72170. return false;
  72171. }
  72172. var ret = true;
  72173. var frameOffset = this._getHighestAnimationFrame() + 1;
  72174. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72175. var boneDict = {};
  72176. var sourceBones = source.bones;
  72177. var nBones;
  72178. var i;
  72179. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72180. boneDict[sourceBones[i].name] = sourceBones[i];
  72181. }
  72182. if (this.bones.length !== sourceBones.length) {
  72183. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72184. ret = false;
  72185. }
  72186. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72187. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72188. var boneName = this.bones[i].name;
  72189. var sourceBone = boneDict[boneName];
  72190. if (sourceBone) {
  72191. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72192. }
  72193. else {
  72194. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72195. ret = false;
  72196. }
  72197. }
  72198. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72199. var range = source.getAnimationRange(name);
  72200. if (range) {
  72201. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72202. }
  72203. return ret;
  72204. };
  72205. Skeleton.prototype.returnToRest = function () {
  72206. for (var index = 0; index < this.bones.length; index++) {
  72207. this.bones[index].returnToRest();
  72208. }
  72209. };
  72210. Skeleton.prototype._getHighestAnimationFrame = function () {
  72211. var ret = 0;
  72212. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72213. if (this.bones[i].animations[0]) {
  72214. var highest = this.bones[i].animations[0].getHighestFrame();
  72215. if (ret < highest) {
  72216. ret = highest;
  72217. }
  72218. }
  72219. }
  72220. return ret;
  72221. };
  72222. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72223. var range = this.getAnimationRange(name);
  72224. if (!range) {
  72225. return null;
  72226. }
  72227. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72228. };
  72229. Skeleton.prototype._markAsDirty = function () {
  72230. this._isDirty = true;
  72231. };
  72232. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72233. this._meshesWithPoseMatrix.push(mesh);
  72234. };
  72235. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72236. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72237. if (index > -1) {
  72238. this._meshesWithPoseMatrix.splice(index, 1);
  72239. }
  72240. };
  72241. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72242. this.onBeforeComputeObservable.notifyObservers(this);
  72243. for (var index = 0; index < this.bones.length; index++) {
  72244. var bone = this.bones[index];
  72245. var parentBone = bone.getParent();
  72246. if (parentBone) {
  72247. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72248. }
  72249. else {
  72250. if (initialSkinMatrix) {
  72251. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72252. }
  72253. else {
  72254. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72255. }
  72256. }
  72257. if (bone._index !== -1) {
  72258. var mappedIndex = bone._index === null ? index : bone._index;
  72259. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72260. }
  72261. }
  72262. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72263. };
  72264. Skeleton.prototype.prepare = function () {
  72265. if (!this._isDirty) {
  72266. return;
  72267. }
  72268. if (this.needInitialSkinMatrix) {
  72269. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72270. var mesh = this._meshesWithPoseMatrix[index];
  72271. var poseMatrix = mesh.getPoseMatrix();
  72272. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72273. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72274. }
  72275. if (this._synchronizedWithMesh !== mesh) {
  72276. this._synchronizedWithMesh = mesh;
  72277. // Prepare bones
  72278. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72279. var bone = this.bones[boneIndex];
  72280. if (!bone.getParent()) {
  72281. var matrix = bone.getBaseMatrix();
  72282. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72283. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72284. }
  72285. }
  72286. }
  72287. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72288. }
  72289. }
  72290. else {
  72291. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72292. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72293. }
  72294. this._computeTransformMatrices(this._transformMatrices, null);
  72295. }
  72296. this._isDirty = false;
  72297. this._scene._activeBones.addCount(this.bones.length, false);
  72298. };
  72299. Skeleton.prototype.getAnimatables = function () {
  72300. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72301. this._animatables = [];
  72302. for (var index = 0; index < this.bones.length; index++) {
  72303. this._animatables.push(this.bones[index]);
  72304. }
  72305. }
  72306. return this._animatables;
  72307. };
  72308. Skeleton.prototype.clone = function (name, id) {
  72309. var result = new Skeleton(name, id || name, this._scene);
  72310. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72311. for (var index = 0; index < this.bones.length; index++) {
  72312. var source = this.bones[index];
  72313. var parentBone = null;
  72314. var parent_1 = source.getParent();
  72315. if (parent_1) {
  72316. var parentIndex = this.bones.indexOf(parent_1);
  72317. parentBone = result.bones[parentIndex];
  72318. }
  72319. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72320. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72321. }
  72322. if (this._ranges) {
  72323. result._ranges = {};
  72324. for (var rangeName in this._ranges) {
  72325. var range = this._ranges[rangeName];
  72326. if (range) {
  72327. result._ranges[rangeName] = range.clone();
  72328. }
  72329. }
  72330. }
  72331. this._isDirty = true;
  72332. return result;
  72333. };
  72334. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72335. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72336. this.bones.forEach(function (bone) {
  72337. bone.animations.forEach(function (animation) {
  72338. animation.enableBlending = true;
  72339. animation.blendingSpeed = blendingSpeed;
  72340. });
  72341. });
  72342. };
  72343. Skeleton.prototype.dispose = function () {
  72344. this._meshesWithPoseMatrix = [];
  72345. // Animations
  72346. this.getScene().stopAnimation(this);
  72347. // Remove from scene
  72348. this.getScene().removeSkeleton(this);
  72349. };
  72350. Skeleton.prototype.serialize = function () {
  72351. var serializationObject = {};
  72352. serializationObject.name = this.name;
  72353. serializationObject.id = this.id;
  72354. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72355. serializationObject.bones = [];
  72356. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72357. for (var index = 0; index < this.bones.length; index++) {
  72358. var bone = this.bones[index];
  72359. var parent_2 = bone.getParent();
  72360. var serializedBone = {
  72361. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72362. name: bone.name,
  72363. matrix: bone.getBaseMatrix().toArray(),
  72364. rest: bone.getRestPose().toArray()
  72365. };
  72366. serializationObject.bones.push(serializedBone);
  72367. if (bone.length) {
  72368. serializedBone.length = bone.length;
  72369. }
  72370. if (bone.animations && bone.animations.length > 0) {
  72371. serializedBone.animation = bone.animations[0].serialize();
  72372. }
  72373. serializationObject.ranges = [];
  72374. for (var name in this._ranges) {
  72375. var source = this._ranges[name];
  72376. if (!source) {
  72377. continue;
  72378. }
  72379. var range = {};
  72380. range.name = name;
  72381. range.from = source.from;
  72382. range.to = source.to;
  72383. serializationObject.ranges.push(range);
  72384. }
  72385. }
  72386. return serializationObject;
  72387. };
  72388. Skeleton.Parse = function (parsedSkeleton, scene) {
  72389. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72390. if (parsedSkeleton.dimensionsAtRest) {
  72391. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72392. }
  72393. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72394. var index;
  72395. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72396. var parsedBone = parsedSkeleton.bones[index];
  72397. var parentBone = null;
  72398. if (parsedBone.parentBoneIndex > -1) {
  72399. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72400. }
  72401. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72402. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72403. if (parsedBone.length) {
  72404. bone.length = parsedBone.length;
  72405. }
  72406. if (parsedBone.animation) {
  72407. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72408. }
  72409. }
  72410. // placed after bones, so createAnimationRange can cascade down
  72411. if (parsedSkeleton.ranges) {
  72412. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72413. var data = parsedSkeleton.ranges[index];
  72414. skeleton.createAnimationRange(data.name, data.from, data.to);
  72415. }
  72416. }
  72417. return skeleton;
  72418. };
  72419. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72420. if (forceUpdate === void 0) { forceUpdate = false; }
  72421. var renderId = this._scene.getRenderId();
  72422. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72423. this.bones[0].computeAbsoluteTransforms();
  72424. this._lastAbsoluteTransformsUpdateId = renderId;
  72425. }
  72426. };
  72427. Skeleton.prototype.getPoseMatrix = function () {
  72428. var poseMatrix = null;
  72429. if (this._meshesWithPoseMatrix.length > 0) {
  72430. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72431. }
  72432. return poseMatrix;
  72433. };
  72434. Skeleton.prototype.sortBones = function () {
  72435. var bones = new Array();
  72436. var visited = new Array(this.bones.length);
  72437. for (var index = 0; index < this.bones.length; index++) {
  72438. this._sortBones(index, bones, visited);
  72439. }
  72440. this.bones = bones;
  72441. };
  72442. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72443. if (visited[index]) {
  72444. return;
  72445. }
  72446. visited[index] = true;
  72447. var bone = this.bones[index];
  72448. if (bone._index === undefined) {
  72449. bone._index = index;
  72450. }
  72451. var parentBone = bone.getParent();
  72452. if (parentBone) {
  72453. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72454. }
  72455. bones.push(bone);
  72456. };
  72457. return Skeleton;
  72458. }());
  72459. BABYLON.Skeleton = Skeleton;
  72460. })(BABYLON || (BABYLON = {}));
  72461. //# sourceMappingURL=babylon.skeleton.js.map
  72462. var BABYLON;
  72463. (function (BABYLON) {
  72464. var SphericalPolynomial = /** @class */ (function () {
  72465. function SphericalPolynomial() {
  72466. this.x = BABYLON.Vector3.Zero();
  72467. this.y = BABYLON.Vector3.Zero();
  72468. this.z = BABYLON.Vector3.Zero();
  72469. this.xx = BABYLON.Vector3.Zero();
  72470. this.yy = BABYLON.Vector3.Zero();
  72471. this.zz = BABYLON.Vector3.Zero();
  72472. this.xy = BABYLON.Vector3.Zero();
  72473. this.yz = BABYLON.Vector3.Zero();
  72474. this.zx = BABYLON.Vector3.Zero();
  72475. }
  72476. SphericalPolynomial.prototype.addAmbient = function (color) {
  72477. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72478. this.xx = this.xx.add(colorVector);
  72479. this.yy = this.yy.add(colorVector);
  72480. this.zz = this.zz.add(colorVector);
  72481. };
  72482. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72483. var result = new SphericalPolynomial();
  72484. result.x = harmonics.L11.scale(1.02333);
  72485. result.y = harmonics.L1_1.scale(1.02333);
  72486. result.z = harmonics.L10.scale(1.02333);
  72487. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72488. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72489. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72490. result.yz = harmonics.L2_1.scale(0.858086);
  72491. result.zx = harmonics.L21.scale(0.858086);
  72492. result.xy = harmonics.L2_2.scale(0.858086);
  72493. result.scale(1.0 / Math.PI);
  72494. return result;
  72495. };
  72496. SphericalPolynomial.prototype.scale = function (scale) {
  72497. this.x = this.x.scale(scale);
  72498. this.y = this.y.scale(scale);
  72499. this.z = this.z.scale(scale);
  72500. this.xx = this.xx.scale(scale);
  72501. this.yy = this.yy.scale(scale);
  72502. this.zz = this.zz.scale(scale);
  72503. this.yz = this.yz.scale(scale);
  72504. this.zx = this.zx.scale(scale);
  72505. this.xy = this.xy.scale(scale);
  72506. };
  72507. return SphericalPolynomial;
  72508. }());
  72509. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72510. var SphericalHarmonics = /** @class */ (function () {
  72511. function SphericalHarmonics() {
  72512. this.L00 = BABYLON.Vector3.Zero();
  72513. this.L1_1 = BABYLON.Vector3.Zero();
  72514. this.L10 = BABYLON.Vector3.Zero();
  72515. this.L11 = BABYLON.Vector3.Zero();
  72516. this.L2_2 = BABYLON.Vector3.Zero();
  72517. this.L2_1 = BABYLON.Vector3.Zero();
  72518. this.L20 = BABYLON.Vector3.Zero();
  72519. this.L21 = BABYLON.Vector3.Zero();
  72520. this.L22 = BABYLON.Vector3.Zero();
  72521. }
  72522. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72523. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72524. var c = colorVector.scale(deltaSolidAngle);
  72525. this.L00 = this.L00.add(c.scale(0.282095));
  72526. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72527. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72528. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72529. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72530. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72531. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72532. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72533. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72534. };
  72535. SphericalHarmonics.prototype.scale = function (scale) {
  72536. this.L00 = this.L00.scale(scale);
  72537. this.L1_1 = this.L1_1.scale(scale);
  72538. this.L10 = this.L10.scale(scale);
  72539. this.L11 = this.L11.scale(scale);
  72540. this.L2_2 = this.L2_2.scale(scale);
  72541. this.L2_1 = this.L2_1.scale(scale);
  72542. this.L20 = this.L20.scale(scale);
  72543. this.L21 = this.L21.scale(scale);
  72544. this.L22 = this.L22.scale(scale);
  72545. };
  72546. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72547. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72548. //
  72549. // E_lm = A_l * L_lm
  72550. //
  72551. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72552. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72553. // the scaling factors are given in equation 9.
  72554. // Constant (Band 0)
  72555. this.L00 = this.L00.scale(3.141593);
  72556. // Linear (Band 1)
  72557. this.L1_1 = this.L1_1.scale(2.094395);
  72558. this.L10 = this.L10.scale(2.094395);
  72559. this.L11 = this.L11.scale(2.094395);
  72560. // Quadratic (Band 2)
  72561. this.L2_2 = this.L2_2.scale(0.785398);
  72562. this.L2_1 = this.L2_1.scale(0.785398);
  72563. this.L20 = this.L20.scale(0.785398);
  72564. this.L21 = this.L21.scale(0.785398);
  72565. this.L22 = this.L22.scale(0.785398);
  72566. };
  72567. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72568. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72569. // L = (1/pi) * E * rho
  72570. //
  72571. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72572. this.scale(1.0 / Math.PI);
  72573. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72574. // (The pixel shader must apply albedo after texture fetches, etc).
  72575. };
  72576. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72577. var result = new SphericalHarmonics();
  72578. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72579. result.L1_1 = polynomial.y.scale(0.977204);
  72580. result.L10 = polynomial.z.scale(0.977204);
  72581. result.L11 = polynomial.x.scale(0.977204);
  72582. result.L2_2 = polynomial.xy.scale(1.16538);
  72583. result.L2_1 = polynomial.yz.scale(1.16538);
  72584. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72585. result.L21 = polynomial.zx.scale(1.16538);
  72586. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72587. result.scale(Math.PI);
  72588. return result;
  72589. };
  72590. return SphericalHarmonics;
  72591. }());
  72592. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72593. })(BABYLON || (BABYLON = {}));
  72594. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72595. var BABYLON;
  72596. (function (BABYLON) {
  72597. var FileFaceOrientation = /** @class */ (function () {
  72598. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72599. this.name = name;
  72600. this.worldAxisForNormal = worldAxisForNormal;
  72601. this.worldAxisForFileX = worldAxisForFileX;
  72602. this.worldAxisForFileY = worldAxisForFileY;
  72603. }
  72604. return FileFaceOrientation;
  72605. }());
  72606. ;
  72607. /**
  72608. * Helper class dealing with the extraction of spherical polynomial dataArray
  72609. * from a cube map.
  72610. */
  72611. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72612. function CubeMapToSphericalPolynomialTools() {
  72613. }
  72614. /**
  72615. * Converts a texture to the according Spherical Polynomial data.
  72616. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72617. *
  72618. * @param texture The texture to extract the information from.
  72619. * @return The Spherical Polynomial data.
  72620. */
  72621. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72622. if (!texture.isCube) {
  72623. // Only supports cube Textures currently.
  72624. return null;
  72625. }
  72626. var size = texture.getSize().width;
  72627. var right = texture.readPixels(0);
  72628. var left = texture.readPixels(1);
  72629. var up;
  72630. var down;
  72631. if (texture.isRenderTarget) {
  72632. up = texture.readPixels(3);
  72633. down = texture.readPixels(2);
  72634. }
  72635. else {
  72636. up = texture.readPixels(2);
  72637. down = texture.readPixels(3);
  72638. }
  72639. var front = texture.readPixels(4);
  72640. var back = texture.readPixels(5);
  72641. var gammaSpace = texture.gammaSpace;
  72642. // Always read as RGBA.
  72643. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72644. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72645. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72646. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72647. }
  72648. var cubeInfo = {
  72649. size: size,
  72650. right: right,
  72651. left: left,
  72652. up: up,
  72653. down: down,
  72654. front: front,
  72655. back: back,
  72656. format: format,
  72657. type: type,
  72658. gammaSpace: gammaSpace,
  72659. };
  72660. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72661. };
  72662. /**
  72663. * Converts a cubemap to the according Spherical Polynomial data.
  72664. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72665. *
  72666. * @param cubeInfo The Cube map to extract the information from.
  72667. * @return The Spherical Polynomial data.
  72668. */
  72669. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72670. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72671. var totalSolidAngle = 0.0;
  72672. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72673. var du = 2.0 / cubeInfo.size;
  72674. var dv = du;
  72675. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72676. var minUV = du * 0.5 - 1.0;
  72677. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72678. var fileFace = this.FileFaces[faceIndex];
  72679. var dataArray = cubeInfo[fileFace.name];
  72680. var v = minUV;
  72681. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72682. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72683. // Because SP is still linear, so summation is fine in that basis.
  72684. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72685. for (var y = 0; y < cubeInfo.size; y++) {
  72686. var u = minUV;
  72687. for (var x = 0; x < cubeInfo.size; x++) {
  72688. // World direction (not normalised)
  72689. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72690. worldDirection.normalize();
  72691. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72692. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72693. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72694. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72695. // Handle Integer types.
  72696. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72697. r /= 255;
  72698. g /= 255;
  72699. b /= 255;
  72700. }
  72701. // Handle Gamma space textures.
  72702. if (cubeInfo.gammaSpace) {
  72703. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72704. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72705. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72706. }
  72707. var color = new BABYLON.Color3(r, g, b);
  72708. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72709. totalSolidAngle += deltaSolidAngle;
  72710. u += du;
  72711. }
  72712. v += dv;
  72713. }
  72714. }
  72715. // Solid angle for entire sphere is 4*pi
  72716. var sphereSolidAngle = 4.0 * Math.PI;
  72717. // Adjust the solid angle to allow for how many faces we processed.
  72718. var facesProcessed = 6.0;
  72719. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72720. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72721. // This is needed because the numerical integration over the cube uses a
  72722. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72723. // and also to compensate for accumulative error due to float precision in the summation.
  72724. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72725. sphericalHarmonics.scale(correctionFactor);
  72726. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72727. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72728. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72729. };
  72730. CubeMapToSphericalPolynomialTools.FileFaces = [
  72731. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72732. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72733. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72734. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72735. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72736. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72737. ];
  72738. return CubeMapToSphericalPolynomialTools;
  72739. }());
  72740. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72741. })(BABYLON || (BABYLON = {}));
  72742. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72743. var BABYLON;
  72744. (function (BABYLON) {
  72745. /**
  72746. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72747. */
  72748. var PanoramaToCubeMapTools = /** @class */ (function () {
  72749. function PanoramaToCubeMapTools() {
  72750. }
  72751. /**
  72752. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72753. *
  72754. * @param float32Array The source data.
  72755. * @param inputWidth The width of the input panorama.
  72756. * @param inputhHeight The height of the input panorama.
  72757. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72758. * @return The cubemap data
  72759. */
  72760. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72761. if (!float32Array) {
  72762. throw "ConvertPanoramaToCubemap: input cannot be null";
  72763. }
  72764. if (float32Array.length != inputWidth * inputHeight * 3) {
  72765. throw "ConvertPanoramaToCubemap: input size is wrong";
  72766. }
  72767. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72768. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72769. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72770. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72771. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72772. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72773. return {
  72774. front: textureFront,
  72775. back: textureBack,
  72776. left: textureLeft,
  72777. right: textureRight,
  72778. up: textureUp,
  72779. down: textureDown,
  72780. size: size,
  72781. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72782. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72783. gammaSpace: false,
  72784. };
  72785. };
  72786. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72787. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72788. var textureArray = new Float32Array(buffer);
  72789. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72790. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72791. var dy = 1 / texSize;
  72792. var fy = 0;
  72793. for (var y = 0; y < texSize; y++) {
  72794. var xv1 = faceData[0];
  72795. var xv2 = faceData[2];
  72796. for (var x = 0; x < texSize; x++) {
  72797. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72798. v.normalize();
  72799. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72800. // 3 channels per pixels
  72801. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72802. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72803. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72804. xv1 = xv1.add(rotDX1);
  72805. xv2 = xv2.add(rotDX2);
  72806. }
  72807. fy += dy;
  72808. }
  72809. return textureArray;
  72810. };
  72811. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72812. var theta = Math.atan2(vDir.z, vDir.x);
  72813. var phi = Math.acos(vDir.y);
  72814. while (theta < -Math.PI)
  72815. theta += 2 * Math.PI;
  72816. while (theta > Math.PI)
  72817. theta -= 2 * Math.PI;
  72818. var dx = theta / Math.PI;
  72819. var dy = phi / Math.PI;
  72820. // recenter.
  72821. dx = dx * 0.5 + 0.5;
  72822. var px = Math.round(dx * inputWidth);
  72823. if (px < 0)
  72824. px = 0;
  72825. else if (px >= inputWidth)
  72826. px = inputWidth - 1;
  72827. var py = Math.round(dy * inputHeight);
  72828. if (py < 0)
  72829. py = 0;
  72830. else if (py >= inputHeight)
  72831. py = inputHeight - 1;
  72832. var inputY = (inputHeight - py - 1);
  72833. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72834. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72835. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72836. return {
  72837. r: r,
  72838. g: g,
  72839. b: b
  72840. };
  72841. };
  72842. PanoramaToCubeMapTools.FACE_FRONT = [
  72843. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72844. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72845. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72846. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72847. ];
  72848. PanoramaToCubeMapTools.FACE_BACK = [
  72849. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72850. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72851. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72852. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72853. ];
  72854. PanoramaToCubeMapTools.FACE_RIGHT = [
  72855. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72856. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72857. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72858. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72859. ];
  72860. PanoramaToCubeMapTools.FACE_LEFT = [
  72861. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72862. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72863. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72864. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72865. ];
  72866. PanoramaToCubeMapTools.FACE_DOWN = [
  72867. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72868. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72869. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72870. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72871. ];
  72872. PanoramaToCubeMapTools.FACE_UP = [
  72873. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72874. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72875. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72876. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72877. ];
  72878. return PanoramaToCubeMapTools;
  72879. }());
  72880. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72881. })(BABYLON || (BABYLON = {}));
  72882. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72883. var BABYLON;
  72884. (function (BABYLON) {
  72885. ;
  72886. /**
  72887. * This groups tools to convert HDR texture to native colors array.
  72888. */
  72889. var HDRTools = /** @class */ (function () {
  72890. function HDRTools() {
  72891. }
  72892. HDRTools.Ldexp = function (mantissa, exponent) {
  72893. if (exponent > 1023) {
  72894. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72895. }
  72896. if (exponent < -1074) {
  72897. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72898. }
  72899. return mantissa * Math.pow(2, exponent);
  72900. };
  72901. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72902. if (exponent > 0) {
  72903. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72904. float32array[index + 0] = red * exponent;
  72905. float32array[index + 1] = green * exponent;
  72906. float32array[index + 2] = blue * exponent;
  72907. }
  72908. else {
  72909. float32array[index + 0] = 0;
  72910. float32array[index + 1] = 0;
  72911. float32array[index + 2] = 0;
  72912. }
  72913. };
  72914. HDRTools.readStringLine = function (uint8array, startIndex) {
  72915. var line = "";
  72916. var character = "";
  72917. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72918. character = String.fromCharCode(uint8array[i]);
  72919. if (character == "\n") {
  72920. break;
  72921. }
  72922. line += character;
  72923. }
  72924. return line;
  72925. };
  72926. /**
  72927. * Reads header information from an RGBE texture stored in a native array.
  72928. * More information on this format are available here:
  72929. * https://en.wikipedia.org/wiki/RGBE_image_format
  72930. *
  72931. * @param uint8array The binary file stored in native array.
  72932. * @return The header information.
  72933. */
  72934. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72935. var height = 0;
  72936. var width = 0;
  72937. var line = this.readStringLine(uint8array, 0);
  72938. if (line[0] != '#' || line[1] != '?') {
  72939. throw "Bad HDR Format.";
  72940. }
  72941. var endOfHeader = false;
  72942. var findFormat = false;
  72943. var lineIndex = 0;
  72944. do {
  72945. lineIndex += (line.length + 1);
  72946. line = this.readStringLine(uint8array, lineIndex);
  72947. if (line == "FORMAT=32-bit_rle_rgbe") {
  72948. findFormat = true;
  72949. }
  72950. else if (line.length == 0) {
  72951. endOfHeader = true;
  72952. }
  72953. } while (!endOfHeader);
  72954. if (!findFormat) {
  72955. throw "HDR Bad header format, unsupported FORMAT";
  72956. }
  72957. lineIndex += (line.length + 1);
  72958. line = this.readStringLine(uint8array, lineIndex);
  72959. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72960. var match = sizeRegexp.exec(line);
  72961. // TODO. Support +Y and -X if needed.
  72962. if (!match || match.length < 3) {
  72963. throw "HDR Bad header format, no size";
  72964. }
  72965. width = parseInt(match[2]);
  72966. height = parseInt(match[1]);
  72967. if (width < 8 || width > 0x7fff) {
  72968. throw "HDR Bad header format, unsupported size";
  72969. }
  72970. lineIndex += (line.length + 1);
  72971. return {
  72972. height: height,
  72973. width: width,
  72974. dataPosition: lineIndex
  72975. };
  72976. };
  72977. /**
  72978. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72979. * This RGBE texture needs to store the information as a panorama.
  72980. *
  72981. * More information on this format are available here:
  72982. * https://en.wikipedia.org/wiki/RGBE_image_format
  72983. *
  72984. * @param buffer The binary file stored in an array buffer.
  72985. * @param size The expected size of the extracted cubemap.
  72986. * @return The Cube Map information.
  72987. */
  72988. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72989. var uint8array = new Uint8Array(buffer);
  72990. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72991. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72992. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72993. return cubeMapData;
  72994. };
  72995. /**
  72996. * Returns the pixels data extracted from an RGBE texture.
  72997. * This pixels will be stored left to right up to down in the R G B order in one array.
  72998. *
  72999. * More information on this format are available here:
  73000. * https://en.wikipedia.org/wiki/RGBE_image_format
  73001. *
  73002. * @param uint8array The binary file stored in an array buffer.
  73003. * @param hdrInfo The header information of the file.
  73004. * @return The pixels data in RGB right to left up to down order.
  73005. */
  73006. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73007. // Keep for multi format supports.
  73008. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73009. };
  73010. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73011. var num_scanlines = hdrInfo.height;
  73012. var scanline_width = hdrInfo.width;
  73013. var a, b, c, d, count;
  73014. var dataIndex = hdrInfo.dataPosition;
  73015. var index = 0, endIndex = 0, i = 0;
  73016. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73017. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73018. // 3 channels of 4 bytes per pixel in float.
  73019. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73020. var resultArray = new Float32Array(resultBuffer);
  73021. // read in each successive scanline
  73022. while (num_scanlines > 0) {
  73023. a = uint8array[dataIndex++];
  73024. b = uint8array[dataIndex++];
  73025. c = uint8array[dataIndex++];
  73026. d = uint8array[dataIndex++];
  73027. if (a != 2 || b != 2 || (c & 0x80)) {
  73028. // this file is not run length encoded
  73029. throw "HDR Bad header format, not RLE";
  73030. }
  73031. if (((c << 8) | d) != scanline_width) {
  73032. throw "HDR Bad header format, wrong scan line width";
  73033. }
  73034. index = 0;
  73035. // read each of the four channels for the scanline into the buffer
  73036. for (i = 0; i < 4; i++) {
  73037. endIndex = (i + 1) * scanline_width;
  73038. while (index < endIndex) {
  73039. a = uint8array[dataIndex++];
  73040. b = uint8array[dataIndex++];
  73041. if (a > 128) {
  73042. // a run of the same value
  73043. count = a - 128;
  73044. if ((count == 0) || (count > endIndex - index)) {
  73045. throw "HDR Bad Format, bad scanline data (run)";
  73046. }
  73047. while (count-- > 0) {
  73048. scanLineArray[index++] = b;
  73049. }
  73050. }
  73051. else {
  73052. // a non-run
  73053. count = a;
  73054. if ((count == 0) || (count > endIndex - index)) {
  73055. throw "HDR Bad Format, bad scanline data (non-run)";
  73056. }
  73057. scanLineArray[index++] = b;
  73058. if (--count > 0) {
  73059. for (var j = 0; j < count; j++) {
  73060. scanLineArray[index++] = uint8array[dataIndex++];
  73061. }
  73062. }
  73063. }
  73064. }
  73065. }
  73066. // now convert data from buffer into floats
  73067. for (i = 0; i < scanline_width; i++) {
  73068. a = scanLineArray[i];
  73069. b = scanLineArray[i + scanline_width];
  73070. c = scanLineArray[i + 2 * scanline_width];
  73071. d = scanLineArray[i + 3 * scanline_width];
  73072. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73073. }
  73074. num_scanlines--;
  73075. }
  73076. return resultArray;
  73077. };
  73078. return HDRTools;
  73079. }());
  73080. BABYLON.HDRTools = HDRTools;
  73081. })(BABYLON || (BABYLON = {}));
  73082. //# sourceMappingURL=babylon.hdr.js.map
  73083. var BABYLON;
  73084. (function (BABYLON) {
  73085. /**
  73086. * This represents a texture coming from an HDR input.
  73087. *
  73088. * The only supported format is currently panorama picture stored in RGBE format.
  73089. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73090. */
  73091. var HDRCubeTexture = /** @class */ (function (_super) {
  73092. __extends(HDRCubeTexture, _super);
  73093. /**
  73094. * Instantiates an HDRTexture from the following parameters.
  73095. *
  73096. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73097. * @param scene The scene the texture will be used in
  73098. * @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.
  73099. * @param noMipmap Forces to not generate the mipmap if true
  73100. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73101. * @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)
  73102. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73103. */
  73104. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73105. if (noMipmap === void 0) { noMipmap = false; }
  73106. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73107. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73108. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73109. if (onLoad === void 0) { onLoad = null; }
  73110. if (onError === void 0) { onError = null; }
  73111. var _this = _super.call(this, scene) || this;
  73112. _this._useInGammaSpace = false;
  73113. _this._generateHarmonics = true;
  73114. _this._isBABYLONPreprocessed = false;
  73115. _this._onLoad = null;
  73116. _this._onError = null;
  73117. /**
  73118. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73119. */
  73120. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73121. /**
  73122. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73123. * This is usefull at run time to apply the good shader.
  73124. */
  73125. _this.isPMREM = false;
  73126. _this._isBlocking = true;
  73127. /**
  73128. * Gets or sets the center of the bounding box associated with the cube texture
  73129. * It must define where the camera used to render the texture was set
  73130. */
  73131. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73132. if (!url) {
  73133. return _this;
  73134. }
  73135. _this.name = url;
  73136. _this.url = url;
  73137. _this.hasAlpha = false;
  73138. _this.isCube = true;
  73139. _this._textureMatrix = BABYLON.Matrix.Identity();
  73140. _this._onLoad = onLoad;
  73141. _this._onError = onError;
  73142. _this.gammaSpace = false;
  73143. var caps = scene.getEngine().getCaps();
  73144. if (size) {
  73145. _this._isBABYLONPreprocessed = false;
  73146. _this._noMipmap = noMipmap;
  73147. _this._size = size;
  73148. _this._useInGammaSpace = useInGammaSpace;
  73149. _this._usePMREMGenerator = usePMREMGenerator &&
  73150. caps.textureLOD &&
  73151. caps.textureFloat &&
  73152. !_this._useInGammaSpace;
  73153. }
  73154. else {
  73155. _this._isBABYLONPreprocessed = true;
  73156. _this._noMipmap = false;
  73157. _this._useInGammaSpace = false;
  73158. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73159. !_this._useInGammaSpace;
  73160. }
  73161. _this.isPMREM = _this._usePMREMGenerator;
  73162. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73163. if (!_this._texture) {
  73164. if (!scene.useDelayedTextureLoading) {
  73165. _this.loadTexture();
  73166. }
  73167. else {
  73168. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73169. }
  73170. }
  73171. return _this;
  73172. }
  73173. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73174. /**
  73175. * Gets wether or not the texture is blocking during loading.
  73176. */
  73177. get: function () {
  73178. return this._isBlocking;
  73179. },
  73180. /**
  73181. * Sets wether or not the texture is blocking during loading.
  73182. */
  73183. set: function (value) {
  73184. this._isBlocking = value;
  73185. },
  73186. enumerable: true,
  73187. configurable: true
  73188. });
  73189. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73190. get: function () {
  73191. return this._boundingBoxSize;
  73192. },
  73193. /**
  73194. * Gets or sets the size of the bounding box associated with the cube texture
  73195. * When defined, the cubemap will switch to local mode
  73196. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73197. * @example https://www.babylonjs-playground.com/#RNASML
  73198. */
  73199. set: function (value) {
  73200. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73201. return;
  73202. }
  73203. this._boundingBoxSize = value;
  73204. var scene = this.getScene();
  73205. if (scene) {
  73206. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73207. }
  73208. },
  73209. enumerable: true,
  73210. configurable: true
  73211. });
  73212. /**
  73213. * Occurs when the file is a preprocessed .babylon.hdr file.
  73214. */
  73215. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73216. var _this = this;
  73217. var mipLevels = 0;
  73218. var floatArrayView = null;
  73219. var scene = this.getScene();
  73220. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73221. var mips = new Array();
  73222. if (!floatArrayView) {
  73223. return mips;
  73224. }
  73225. var startIndex = 30;
  73226. for (var level = 0; level < mipLevels; level++) {
  73227. mips.push([]);
  73228. // Fill each pixel of the mip level.
  73229. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73230. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73231. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73232. mips[level].push(faceData);
  73233. startIndex += faceSize;
  73234. }
  73235. }
  73236. return mips;
  73237. } : null;
  73238. var callback = function (buffer) {
  73239. var scene = _this.getScene();
  73240. if (!scene) {
  73241. return null;
  73242. }
  73243. // Create Native Array Views
  73244. var intArrayView = new Int32Array(buffer);
  73245. floatArrayView = new Float32Array(buffer);
  73246. // Fill header.
  73247. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73248. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73249. // Update Texture Information.
  73250. if (!_this._texture) {
  73251. return null;
  73252. }
  73253. _this._texture.updateSize(_this._size, _this._size);
  73254. // Fill polynomial information.
  73255. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73256. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73257. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73258. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73259. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73260. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73261. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73262. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73263. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73264. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73265. _this.sphericalPolynomial = sphericalPolynomial;
  73266. // Fill pixel data.
  73267. mipLevels = intArrayView[29]; // Number of mip levels.
  73268. var startIndex = 30;
  73269. var data = [];
  73270. var faceSize = Math.pow(_this._size, 2) * 3;
  73271. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73272. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73273. startIndex += faceSize;
  73274. }
  73275. var results = [];
  73276. var byteArray = null;
  73277. // Push each faces.
  73278. for (var k = 0; k < 6; k++) {
  73279. var dataFace = null;
  73280. // To be deprecated.
  73281. if (version === 1) {
  73282. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73283. dataFace = data[j];
  73284. }
  73285. // If special cases.
  73286. if (!mipmapGenerator && dataFace) {
  73287. if (!scene.getEngine().getCaps().textureFloat) {
  73288. // 3 channels of 1 bytes per pixel in bytes.
  73289. var byteBuffer = new ArrayBuffer(faceSize);
  73290. byteArray = new Uint8Array(byteBuffer);
  73291. }
  73292. for (var i = 0; i < _this._size * _this._size; i++) {
  73293. // Put in gamma space if requested.
  73294. if (_this._useInGammaSpace) {
  73295. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73296. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73297. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73298. }
  73299. // Convert to int texture for fallback.
  73300. if (byteArray) {
  73301. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73302. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73303. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73304. // May use luminance instead if the result is not accurate.
  73305. var max = Math.max(Math.max(r, g), b);
  73306. if (max > 255) {
  73307. var scale = 255 / max;
  73308. r *= scale;
  73309. g *= scale;
  73310. b *= scale;
  73311. }
  73312. byteArray[(i * 3) + 0] = r;
  73313. byteArray[(i * 3) + 1] = g;
  73314. byteArray[(i * 3) + 2] = b;
  73315. }
  73316. }
  73317. }
  73318. // Fill the array accordingly.
  73319. if (byteArray) {
  73320. results.push(byteArray);
  73321. }
  73322. else {
  73323. results.push(dataFace);
  73324. }
  73325. }
  73326. return results;
  73327. };
  73328. if (scene) {
  73329. 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);
  73330. }
  73331. };
  73332. /**
  73333. * Occurs when the file is raw .hdr file.
  73334. */
  73335. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73336. var _this = this;
  73337. var callback = function (buffer) {
  73338. var scene = _this.getScene();
  73339. if (!scene) {
  73340. return null;
  73341. }
  73342. // Extract the raw linear data.
  73343. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73344. // Generate harmonics if needed.
  73345. if (_this._generateHarmonics) {
  73346. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73347. _this.sphericalPolynomial = sphericalPolynomial;
  73348. }
  73349. var results = [];
  73350. var byteArray = null;
  73351. // Push each faces.
  73352. for (var j = 0; j < 6; j++) {
  73353. // Create uintarray fallback.
  73354. if (!scene.getEngine().getCaps().textureFloat) {
  73355. // 3 channels of 1 bytes per pixel in bytes.
  73356. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73357. byteArray = new Uint8Array(byteBuffer);
  73358. }
  73359. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73360. // If special cases.
  73361. if (_this._useInGammaSpace || byteArray) {
  73362. for (var i = 0; i < _this._size * _this._size; i++) {
  73363. // Put in gamma space if requested.
  73364. if (_this._useInGammaSpace) {
  73365. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73366. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73367. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73368. }
  73369. // Convert to int texture for fallback.
  73370. if (byteArray) {
  73371. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73372. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73373. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73374. // May use luminance instead if the result is not accurate.
  73375. var max = Math.max(Math.max(r, g), b);
  73376. if (max > 255) {
  73377. var scale = 255 / max;
  73378. r *= scale;
  73379. g *= scale;
  73380. b *= scale;
  73381. }
  73382. byteArray[(i * 3) + 0] = r;
  73383. byteArray[(i * 3) + 1] = g;
  73384. byteArray[(i * 3) + 2] = b;
  73385. }
  73386. }
  73387. }
  73388. if (byteArray) {
  73389. results.push(byteArray);
  73390. }
  73391. else {
  73392. results.push(dataFace);
  73393. }
  73394. }
  73395. return results;
  73396. };
  73397. var mipmapGenerator = null;
  73398. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73399. // if (!this._noMipmap &&
  73400. // this._usePMREMGenerator) {
  73401. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73402. // // Custom setup of the generator matching with the PBR shader values.
  73403. // var generator = new BABYLON.PMREMGenerator(data,
  73404. // this._size,
  73405. // this._size,
  73406. // 0,
  73407. // 3,
  73408. // this.getScene().getEngine().getCaps().textureFloat,
  73409. // 2048,
  73410. // 0.25,
  73411. // false,
  73412. // true);
  73413. // return generator.filterCubeMap();
  73414. // };
  73415. // }
  73416. var scene = this.getScene();
  73417. if (scene) {
  73418. 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);
  73419. }
  73420. };
  73421. /**
  73422. * Starts the loading process of the texture.
  73423. */
  73424. HDRCubeTexture.prototype.loadTexture = function () {
  73425. if (this._isBABYLONPreprocessed) {
  73426. this.loadBabylonTexture();
  73427. }
  73428. else {
  73429. this.loadHDRTexture();
  73430. }
  73431. };
  73432. HDRCubeTexture.prototype.clone = function () {
  73433. var scene = this.getScene();
  73434. if (!scene) {
  73435. return this;
  73436. }
  73437. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73438. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73439. // Base texture
  73440. newTexture.level = this.level;
  73441. newTexture.wrapU = this.wrapU;
  73442. newTexture.wrapV = this.wrapV;
  73443. newTexture.coordinatesIndex = this.coordinatesIndex;
  73444. newTexture.coordinatesMode = this.coordinatesMode;
  73445. return newTexture;
  73446. };
  73447. // Methods
  73448. HDRCubeTexture.prototype.delayLoad = function () {
  73449. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73450. return;
  73451. }
  73452. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73453. this._texture = this._getFromCache(this.url, this._noMipmap);
  73454. if (!this._texture) {
  73455. this.loadTexture();
  73456. }
  73457. };
  73458. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73459. return this._textureMatrix;
  73460. };
  73461. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73462. this._textureMatrix = value;
  73463. };
  73464. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73465. var texture = null;
  73466. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73467. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73468. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73469. texture.name = parsedTexture.name;
  73470. texture.hasAlpha = parsedTexture.hasAlpha;
  73471. texture.level = parsedTexture.level;
  73472. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73473. texture.isBlocking = parsedTexture.isBlocking;
  73474. }
  73475. if (texture) {
  73476. if (parsedTexture.boundingBoxPosition) {
  73477. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73478. }
  73479. if (parsedTexture.boundingBoxSize) {
  73480. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73481. }
  73482. }
  73483. return texture;
  73484. };
  73485. HDRCubeTexture.prototype.serialize = function () {
  73486. if (!this.name) {
  73487. return null;
  73488. }
  73489. var serializationObject = {};
  73490. serializationObject.name = this.name;
  73491. serializationObject.hasAlpha = this.hasAlpha;
  73492. serializationObject.isCube = true;
  73493. serializationObject.level = this.level;
  73494. serializationObject.size = this._size;
  73495. serializationObject.coordinatesMode = this.coordinatesMode;
  73496. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73497. serializationObject.generateHarmonics = this._generateHarmonics;
  73498. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73499. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73500. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73501. serializationObject.noMipmap = this._noMipmap;
  73502. serializationObject.isBlocking = this._isBlocking;
  73503. return serializationObject;
  73504. };
  73505. /**
  73506. * Saves as a file the data contained in the texture in a binary format.
  73507. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73508. * as the spherical used in the lighting.
  73509. * @param url The HDR file url.
  73510. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73511. * @param onError Method called if any error happens during download.
  73512. * @return The packed binary data.
  73513. */
  73514. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73515. if (onError === void 0) { onError = null; }
  73516. var callback = function (buffer) {
  73517. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73518. // Returns a URL you can use as a href.
  73519. var objUrl = window.URL.createObjectURL(data);
  73520. // Simulates a link to it and click to dowload.
  73521. var a = document.createElement("a");
  73522. document.body.appendChild(a);
  73523. a.style.display = "none";
  73524. a.href = objUrl;
  73525. a.download = "envmap.babylon.hdr";
  73526. a.click();
  73527. };
  73528. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73529. };
  73530. /**
  73531. * Serializes the data contained in the texture in a binary format.
  73532. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73533. * as the spherical used in the lighting.
  73534. * @param url The HDR file url.
  73535. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73536. * @param onError Method called if any error happens during download.
  73537. * @return The packed binary data.
  73538. */
  73539. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73540. if (onError === void 0) { onError = null; }
  73541. // Needs the url tho create the texture.
  73542. if (!url) {
  73543. return;
  73544. }
  73545. // Check Power of two size.
  73546. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73547. return;
  73548. }
  73549. // Coming Back in 3.x.
  73550. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73551. };
  73552. HDRCubeTexture._facesMapping = [
  73553. "right",
  73554. "left",
  73555. "up",
  73556. "down",
  73557. "front",
  73558. "back"
  73559. ];
  73560. return HDRCubeTexture;
  73561. }(BABYLON.BaseTexture));
  73562. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73563. })(BABYLON || (BABYLON = {}));
  73564. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73565. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73566. // Huge respect for a such great lib.
  73567. // Earcut license:
  73568. // Copyright (c) 2016, Mapbox
  73569. //
  73570. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73571. // with or without fee is hereby granted, provided that the above copyright notice
  73572. // and this permission notice appear in all copies.
  73573. //
  73574. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73575. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73576. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73577. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73578. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73579. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73580. // THIS SOFTWARE.
  73581. var Earcut;
  73582. (function (Earcut) {
  73583. /**
  73584. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73585. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73586. * @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).
  73587. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73588. */
  73589. function earcut(data, holeIndices, dim) {
  73590. dim = dim || 2;
  73591. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73592. if (!outerNode)
  73593. return triangles;
  73594. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73595. if (hasHoles)
  73596. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73597. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73598. if (data.length > 80 * dim) {
  73599. minX = maxX = data[0];
  73600. minY = maxY = data[1];
  73601. for (var i = dim; i < outerLen; i += dim) {
  73602. x = data[i];
  73603. y = data[i + 1];
  73604. if (x < minX)
  73605. minX = x;
  73606. if (y < minY)
  73607. minY = y;
  73608. if (x > maxX)
  73609. maxX = x;
  73610. if (y > maxY)
  73611. maxY = y;
  73612. }
  73613. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73614. size = Math.max(maxX - minX, maxY - minY);
  73615. }
  73616. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73617. return triangles;
  73618. }
  73619. Earcut.earcut = earcut;
  73620. var Node = /** @class */ (function () {
  73621. function Node(i, x, y) {
  73622. this.i = i;
  73623. this.x = x;
  73624. this.y = y;
  73625. this.prev = null;
  73626. this.next = null;
  73627. this.z = null;
  73628. this.prevZ = null;
  73629. this.nextZ = null;
  73630. this.steiner = false;
  73631. }
  73632. return Node;
  73633. }());
  73634. // create a circular doubly linked list from polygon points in the specified winding order
  73635. function linkedList(data, start, end, dim, clockwise) {
  73636. var i, last = null;
  73637. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73638. for (i = start; i < end; i += dim)
  73639. last = insertNode(i, data[i], data[i + 1], last);
  73640. }
  73641. else {
  73642. for (i = end - dim; i >= start; i -= dim)
  73643. last = insertNode(i, data[i], data[i + 1], last);
  73644. }
  73645. if (last && equals(last, last.next)) {
  73646. removeNode(last);
  73647. last = last.next;
  73648. }
  73649. return last;
  73650. }
  73651. // eliminate colinear or duplicate points
  73652. function filterPoints(start, end) {
  73653. if (!start)
  73654. return start;
  73655. if (!end)
  73656. end = start;
  73657. var p = start, again;
  73658. do {
  73659. again = false;
  73660. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73661. removeNode(p);
  73662. p = end = p.prev;
  73663. if (p === p.next)
  73664. return undefined;
  73665. again = true;
  73666. }
  73667. else {
  73668. p = p.next;
  73669. }
  73670. } while (again || p !== end);
  73671. return end;
  73672. }
  73673. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73674. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73675. if (!ear)
  73676. return;
  73677. // interlink polygon nodes in z-order
  73678. if (!pass && size)
  73679. indexCurve(ear, minX, minY, size);
  73680. var stop = ear, prev, next;
  73681. // iterate through ears, slicing them one by one
  73682. while (ear.prev !== ear.next) {
  73683. prev = ear.prev;
  73684. next = ear.next;
  73685. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73686. // cut off the triangle
  73687. triangles.push(prev.i / dim);
  73688. triangles.push(ear.i / dim);
  73689. triangles.push(next.i / dim);
  73690. removeNode(ear);
  73691. // skipping the next vertice leads to less sliver triangles
  73692. ear = next.next;
  73693. stop = next.next;
  73694. continue;
  73695. }
  73696. ear = next;
  73697. // if we looped through the whole remaining polygon and can't find any more ears
  73698. if (ear === stop) {
  73699. // try filtering points and slicing again
  73700. if (!pass) {
  73701. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73702. // if this didn't work, try curing all small self-intersections locally
  73703. }
  73704. else if (pass === 1) {
  73705. ear = cureLocalIntersections(ear, triangles, dim);
  73706. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73707. // as a last resort, try splitting the remaining polygon into two
  73708. }
  73709. else if (pass === 2) {
  73710. splitEarcut(ear, triangles, dim, minX, minY, size);
  73711. }
  73712. break;
  73713. }
  73714. }
  73715. }
  73716. // check whether a polygon node forms a valid ear with adjacent nodes
  73717. function isEar(ear) {
  73718. var a = ear.prev, b = ear, c = ear.next;
  73719. if (area(a, b, c) >= 0)
  73720. return false; // reflex, can't be an ear
  73721. // now make sure we don't have other points inside the potential ear
  73722. var p = ear.next.next;
  73723. while (p !== ear.prev) {
  73724. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73725. area(p.prev, p, p.next) >= 0)
  73726. return false;
  73727. p = p.next;
  73728. }
  73729. return true;
  73730. }
  73731. function isEarHashed(ear, minX, minY, size) {
  73732. var a = ear.prev, b = ear, c = ear.next;
  73733. if (area(a, b, c) >= 0)
  73734. return false; // reflex, can't be an ear
  73735. // triangle bbox; min & max are calculated like this for speed
  73736. 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);
  73737. // z-order range for the current triangle bbox;
  73738. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73739. // first look for points inside the triangle in increasing z-order
  73740. var p = ear.nextZ;
  73741. while (p && p.z <= maxZ) {
  73742. if (p !== ear.prev &&
  73743. p !== ear.next &&
  73744. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73745. area(p.prev, p, p.next) >= 0)
  73746. return false;
  73747. p = p.nextZ;
  73748. }
  73749. // then look for points in decreasing z-order
  73750. p = ear.prevZ;
  73751. while (p && p.z >= minZ) {
  73752. if (p !== ear.prev &&
  73753. p !== ear.next &&
  73754. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73755. area(p.prev, p, p.next) >= 0)
  73756. return false;
  73757. p = p.prevZ;
  73758. }
  73759. return true;
  73760. }
  73761. // go through all polygon nodes and cure small local self-intersections
  73762. function cureLocalIntersections(start, triangles, dim) {
  73763. var p = start;
  73764. do {
  73765. var a = p.prev, b = p.next.next;
  73766. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73767. triangles.push(a.i / dim);
  73768. triangles.push(p.i / dim);
  73769. triangles.push(b.i / dim);
  73770. // remove two nodes involved
  73771. removeNode(p);
  73772. removeNode(p.next);
  73773. p = start = b;
  73774. }
  73775. p = p.next;
  73776. } while (p !== start);
  73777. return p;
  73778. }
  73779. // try splitting polygon into two and triangulate them independently
  73780. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73781. // look for a valid diagonal that divides the polygon into two
  73782. var a = start;
  73783. do {
  73784. var b = a.next.next;
  73785. while (b !== a.prev) {
  73786. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73787. // split the polygon in two by the diagonal
  73788. var c = splitPolygon(a, b);
  73789. // filter colinear points around the cuts
  73790. a = filterPoints(a, a.next);
  73791. c = filterPoints(c, c.next);
  73792. // run earcut on each half
  73793. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73794. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73795. return;
  73796. }
  73797. b = b.next;
  73798. }
  73799. a = a.next;
  73800. } while (a !== start);
  73801. }
  73802. // link every hole into the outer loop, producing a single-ring polygon without holes
  73803. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73804. var queue = [], i, len, start, end, list;
  73805. for (i = 0, len = holeIndices.length; i < len; i++) {
  73806. start = holeIndices[i] * dim;
  73807. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73808. list = linkedList(data, start, end, dim, false);
  73809. if (list === list.next)
  73810. list.steiner = true;
  73811. queue.push(getLeftmost(list));
  73812. }
  73813. queue.sort(compareX);
  73814. // process holes from left to right
  73815. for (i = 0; i < queue.length; i++) {
  73816. eliminateHole(queue[i], outerNode);
  73817. outerNode = filterPoints(outerNode, outerNode.next);
  73818. }
  73819. return outerNode;
  73820. }
  73821. function compareX(a, b) {
  73822. return a.x - b.x;
  73823. }
  73824. // find a bridge between vertices that connects hole with an outer ring and and link it
  73825. function eliminateHole(hole, outerNode) {
  73826. outerNode = findHoleBridge(hole, outerNode);
  73827. if (outerNode) {
  73828. var b = splitPolygon(outerNode, hole);
  73829. filterPoints(b, b.next);
  73830. }
  73831. }
  73832. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73833. function findHoleBridge(hole, outerNode) {
  73834. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73835. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73836. // segment's endpoint with lesser x will be potential connection point
  73837. do {
  73838. if (hy <= p.y && hy >= p.next.y) {
  73839. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73840. if (x <= hx && x > qx) {
  73841. qx = x;
  73842. if (x === hx) {
  73843. if (hy === p.y)
  73844. return p;
  73845. if (hy === p.next.y)
  73846. return p.next;
  73847. }
  73848. m = p.x < p.next.x ? p : p.next;
  73849. }
  73850. }
  73851. p = p.next;
  73852. } while (p !== outerNode);
  73853. if (!m)
  73854. return null;
  73855. if (hx === qx)
  73856. return m.prev; // hole touches outer segment; pick lower endpoint
  73857. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73858. // if there are no points found, we have a valid connection;
  73859. // otherwise choose the point of the minimum angle with the ray as connection point
  73860. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73861. p = m.next;
  73862. while (p !== stop) {
  73863. if (hx >= p.x &&
  73864. p.x >= mx &&
  73865. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73866. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73867. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73868. m = p;
  73869. tanMin = tan;
  73870. }
  73871. }
  73872. p = p.next;
  73873. }
  73874. return m;
  73875. }
  73876. // interlink polygon nodes in z-order
  73877. function indexCurve(start, minX, minY, size) {
  73878. var p = start;
  73879. do {
  73880. if (p.z === null)
  73881. p.z = zOrder(p.x, p.y, minX, minY, size);
  73882. p.prevZ = p.prev;
  73883. p.nextZ = p.next;
  73884. p = p.next;
  73885. } while (p !== start);
  73886. p.prevZ.nextZ = null;
  73887. p.prevZ = null;
  73888. sortLinked(p);
  73889. }
  73890. // Simon Tatham's linked list merge sort algorithm
  73891. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73892. function sortLinked(list) {
  73893. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73894. do {
  73895. p = list;
  73896. list = null;
  73897. tail = null;
  73898. numMerges = 0;
  73899. while (p) {
  73900. numMerges++;
  73901. q = p;
  73902. pSize = 0;
  73903. for (i = 0; i < inSize; i++) {
  73904. pSize++;
  73905. q = q.nextZ;
  73906. if (!q)
  73907. break;
  73908. }
  73909. qSize = inSize;
  73910. while (pSize > 0 || (qSize > 0 && q)) {
  73911. if (pSize === 0) {
  73912. e = q;
  73913. q = q.nextZ;
  73914. qSize--;
  73915. }
  73916. else if (qSize === 0 || !q) {
  73917. e = p;
  73918. p = p.nextZ;
  73919. pSize--;
  73920. }
  73921. else if (p.z <= q.z) {
  73922. e = p;
  73923. p = p.nextZ;
  73924. pSize--;
  73925. }
  73926. else {
  73927. e = q;
  73928. q = q.nextZ;
  73929. qSize--;
  73930. }
  73931. if (tail)
  73932. tail.nextZ = e;
  73933. else
  73934. list = e;
  73935. e.prevZ = tail;
  73936. tail = e;
  73937. }
  73938. p = q;
  73939. }
  73940. tail.nextZ = null;
  73941. inSize *= 2;
  73942. } while (numMerges > 1);
  73943. return list;
  73944. }
  73945. // z-order of a point given coords and size of the data bounding box
  73946. function zOrder(x, y, minX, minY, size) {
  73947. // coords are transformed into non-negative 15-bit integer range
  73948. x = 32767 * (x - minX) / size;
  73949. y = 32767 * (y - minY) / size;
  73950. x = (x | (x << 8)) & 0x00FF00FF;
  73951. x = (x | (x << 4)) & 0x0F0F0F0F;
  73952. x = (x | (x << 2)) & 0x33333333;
  73953. x = (x | (x << 1)) & 0x55555555;
  73954. y = (y | (y << 8)) & 0x00FF00FF;
  73955. y = (y | (y << 4)) & 0x0F0F0F0F;
  73956. y = (y | (y << 2)) & 0x33333333;
  73957. y = (y | (y << 1)) & 0x55555555;
  73958. return x | (y << 1);
  73959. }
  73960. // find the leftmost node of a polygon ring
  73961. function getLeftmost(start) {
  73962. var p = start, leftmost = start;
  73963. do {
  73964. if (p.x < leftmost.x)
  73965. leftmost = p;
  73966. p = p.next;
  73967. } while (p !== start);
  73968. return leftmost;
  73969. }
  73970. // check if a point lies within a convex triangle
  73971. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73972. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73973. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73974. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73975. }
  73976. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73977. function isValidDiagonal(a, b) {
  73978. return a.next.i !== b.i &&
  73979. a.prev.i !== b.i &&
  73980. !intersectsPolygon(a, b) &&
  73981. locallyInside(a, b) &&
  73982. locallyInside(b, a) &&
  73983. middleInside(a, b);
  73984. }
  73985. // signed area of a triangle
  73986. function area(p, q, r) {
  73987. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73988. }
  73989. // check if two points are equal
  73990. function equals(p1, p2) {
  73991. return p1.x === p2.x && p1.y === p2.y;
  73992. }
  73993. // check if two segments intersect
  73994. function intersects(p1, q1, p2, q2) {
  73995. if ((equals(p1, q1) && equals(p2, q2)) ||
  73996. (equals(p1, q2) && equals(p2, q1)))
  73997. return true;
  73998. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73999. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74000. }
  74001. // check if a polygon diagonal intersects any polygon segments
  74002. function intersectsPolygon(a, b) {
  74003. var p = a;
  74004. do {
  74005. if (p.i !== a.i &&
  74006. p.next.i !== a.i &&
  74007. p.i !== b.i &&
  74008. p.next.i !== b.i &&
  74009. intersects(p, p.next, a, b))
  74010. return true;
  74011. p = p.next;
  74012. } while (p !== a);
  74013. return false;
  74014. }
  74015. // check if a polygon diagonal is locally inside the polygon
  74016. function locallyInside(a, b) {
  74017. return area(a.prev, a, a.next) < 0
  74018. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74019. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74020. }
  74021. // check if the middle point of a polygon diagonal is inside the polygon
  74022. function middleInside(a, b) {
  74023. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74024. do {
  74025. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74026. inside = !inside;
  74027. p = p.next;
  74028. } while (p !== a);
  74029. return inside;
  74030. }
  74031. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74032. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74033. function splitPolygon(a, b) {
  74034. 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;
  74035. a.next = b;
  74036. b.prev = a;
  74037. a2.next = an;
  74038. an.prev = a2;
  74039. b2.next = a2;
  74040. a2.prev = b2;
  74041. bp.next = b2;
  74042. b2.prev = bp;
  74043. return b2;
  74044. }
  74045. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74046. function insertNode(i, x, y, last) {
  74047. var p = new Node(i, x, y);
  74048. if (!last) {
  74049. p.prev = p;
  74050. p.next = p;
  74051. }
  74052. else {
  74053. p.next = last.next;
  74054. p.prev = last;
  74055. last.next.prev = p;
  74056. last.next = p;
  74057. }
  74058. return p;
  74059. }
  74060. function removeNode(p) {
  74061. p.next.prev = p.prev;
  74062. p.prev.next = p.next;
  74063. if (p.prevZ)
  74064. p.prevZ.nextZ = p.nextZ;
  74065. if (p.nextZ)
  74066. p.nextZ.prevZ = p.prevZ;
  74067. }
  74068. /**
  74069. * return a percentage difference between the polygon area and its triangulation area;
  74070. * used to verify correctness of triangulation
  74071. */
  74072. function deviation(data, holeIndices, dim, triangles) {
  74073. var hasHoles = holeIndices && holeIndices.length;
  74074. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74075. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74076. if (hasHoles) {
  74077. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74078. var start = holeIndices[i] * dim;
  74079. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74080. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74081. }
  74082. }
  74083. var trianglesArea = 0;
  74084. for (i = 0; i < triangles.length; i += 3) {
  74085. var a = triangles[i] * dim;
  74086. var b = triangles[i + 1] * dim;
  74087. var c = triangles[i + 2] * dim;
  74088. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74089. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74090. }
  74091. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74092. }
  74093. Earcut.deviation = deviation;
  74094. ;
  74095. function signedArea(data, start, end, dim) {
  74096. var sum = 0;
  74097. for (var i = start, j = end - dim; i < end; i += dim) {
  74098. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74099. j = i;
  74100. }
  74101. return sum;
  74102. }
  74103. /**
  74104. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74105. */
  74106. function flatten(data) {
  74107. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74108. for (var i = 0; i < data.length; i++) {
  74109. for (var j = 0; j < data[i].length; j++) {
  74110. for (var d = 0; d < dim; d++)
  74111. result.vertices.push(data[i][j][d]);
  74112. }
  74113. if (i > 0) {
  74114. holeIndex += data[i - 1].length;
  74115. result.holes.push(holeIndex);
  74116. }
  74117. }
  74118. return result;
  74119. }
  74120. Earcut.flatten = flatten;
  74121. ;
  74122. })(Earcut || (Earcut = {}));
  74123. //# sourceMappingURL=babylon.earcut.js.map
  74124. var BABYLON;
  74125. (function (BABYLON) {
  74126. var IndexedVector2 = /** @class */ (function (_super) {
  74127. __extends(IndexedVector2, _super);
  74128. function IndexedVector2(original, index) {
  74129. var _this = _super.call(this, original.x, original.y) || this;
  74130. _this.index = index;
  74131. return _this;
  74132. }
  74133. return IndexedVector2;
  74134. }(BABYLON.Vector2));
  74135. var PolygonPoints = /** @class */ (function () {
  74136. function PolygonPoints() {
  74137. this.elements = new Array();
  74138. }
  74139. PolygonPoints.prototype.add = function (originalPoints) {
  74140. var _this = this;
  74141. var result = new Array();
  74142. originalPoints.forEach(function (point) {
  74143. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74144. var newPoint = new IndexedVector2(point, _this.elements.length);
  74145. result.push(newPoint);
  74146. _this.elements.push(newPoint);
  74147. }
  74148. });
  74149. return result;
  74150. };
  74151. PolygonPoints.prototype.computeBounds = function () {
  74152. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74153. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74154. this.elements.forEach(function (point) {
  74155. // x
  74156. if (point.x < lmin.x) {
  74157. lmin.x = point.x;
  74158. }
  74159. else if (point.x > lmax.x) {
  74160. lmax.x = point.x;
  74161. }
  74162. // y
  74163. if (point.y < lmin.y) {
  74164. lmin.y = point.y;
  74165. }
  74166. else if (point.y > lmax.y) {
  74167. lmax.y = point.y;
  74168. }
  74169. });
  74170. return {
  74171. min: lmin,
  74172. max: lmax,
  74173. width: lmax.x - lmin.x,
  74174. height: lmax.y - lmin.y
  74175. };
  74176. };
  74177. return PolygonPoints;
  74178. }());
  74179. var Polygon = /** @class */ (function () {
  74180. function Polygon() {
  74181. }
  74182. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74183. return [
  74184. new BABYLON.Vector2(xmin, ymin),
  74185. new BABYLON.Vector2(xmax, ymin),
  74186. new BABYLON.Vector2(xmax, ymax),
  74187. new BABYLON.Vector2(xmin, ymax)
  74188. ];
  74189. };
  74190. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74191. if (cx === void 0) { cx = 0; }
  74192. if (cy === void 0) { cy = 0; }
  74193. if (numberOfSides === void 0) { numberOfSides = 32; }
  74194. var result = new Array();
  74195. var angle = 0;
  74196. var increment = (Math.PI * 2) / numberOfSides;
  74197. for (var i = 0; i < numberOfSides; i++) {
  74198. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74199. angle -= increment;
  74200. }
  74201. return result;
  74202. };
  74203. Polygon.Parse = function (input) {
  74204. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74205. var i, result = [];
  74206. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74207. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74208. }
  74209. return result;
  74210. };
  74211. Polygon.StartingAt = function (x, y) {
  74212. return BABYLON.Path2.StartingAt(x, y);
  74213. };
  74214. return Polygon;
  74215. }());
  74216. BABYLON.Polygon = Polygon;
  74217. var PolygonMeshBuilder = /** @class */ (function () {
  74218. function PolygonMeshBuilder(name, contours, scene) {
  74219. this._points = new PolygonPoints();
  74220. this._outlinepoints = new PolygonPoints();
  74221. this._holes = new Array();
  74222. this._epoints = new Array();
  74223. this._eholes = new Array();
  74224. this._name = name;
  74225. this._scene = scene;
  74226. var points;
  74227. if (contours instanceof BABYLON.Path2) {
  74228. points = contours.getPoints();
  74229. }
  74230. else {
  74231. points = contours;
  74232. }
  74233. this._addToepoint(points);
  74234. this._points.add(points);
  74235. this._outlinepoints.add(points);
  74236. }
  74237. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74238. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74239. var p = points_1[_i];
  74240. this._epoints.push(p.x, p.y);
  74241. }
  74242. };
  74243. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74244. this._points.add(hole);
  74245. var holepoints = new PolygonPoints();
  74246. holepoints.add(hole);
  74247. this._holes.push(holepoints);
  74248. this._eholes.push(this._epoints.length / 2);
  74249. this._addToepoint(hole);
  74250. return this;
  74251. };
  74252. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74253. var _this = this;
  74254. if (updatable === void 0) { updatable = false; }
  74255. if (depth === void 0) { depth = 0; }
  74256. var result = new BABYLON.Mesh(this._name, this._scene);
  74257. var normals = new Array();
  74258. var positions = new Array();
  74259. var uvs = new Array();
  74260. var bounds = this._points.computeBounds();
  74261. this._points.elements.forEach(function (p) {
  74262. normals.push(0, 1.0, 0);
  74263. positions.push(p.x, 0, p.y);
  74264. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74265. });
  74266. var indices = new Array();
  74267. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74268. for (var i = 0; i < res.length; i++) {
  74269. indices.push(res[i]);
  74270. }
  74271. if (depth > 0) {
  74272. var positionscount = (positions.length / 3); //get the current pointcount
  74273. this._points.elements.forEach(function (p) {
  74274. normals.push(0, -1.0, 0);
  74275. positions.push(p.x, -depth, p.y);
  74276. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74277. });
  74278. var totalCount = indices.length;
  74279. for (var i = 0; i < totalCount; i += 3) {
  74280. var i0 = indices[i + 0];
  74281. var i1 = indices[i + 1];
  74282. var i2 = indices[i + 2];
  74283. indices.push(i2 + positionscount);
  74284. indices.push(i1 + positionscount);
  74285. indices.push(i0 + positionscount);
  74286. }
  74287. //Add the sides
  74288. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74289. this._holes.forEach(function (hole) {
  74290. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74291. });
  74292. }
  74293. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74294. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74295. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74296. result.setIndices(indices);
  74297. return result;
  74298. };
  74299. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74300. var StartIndex = positions.length / 3;
  74301. var ulength = 0;
  74302. for (var i = 0; i < points.elements.length; i++) {
  74303. var p = points.elements[i];
  74304. var p1;
  74305. if ((i + 1) > points.elements.length - 1) {
  74306. p1 = points.elements[0];
  74307. }
  74308. else {
  74309. p1 = points.elements[i + 1];
  74310. }
  74311. positions.push(p.x, 0, p.y);
  74312. positions.push(p.x, -depth, p.y);
  74313. positions.push(p1.x, 0, p1.y);
  74314. positions.push(p1.x, -depth, p1.y);
  74315. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74316. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74317. var v3 = v2.subtract(v1);
  74318. var v4 = new BABYLON.Vector3(0, 1, 0);
  74319. var vn = BABYLON.Vector3.Cross(v3, v4);
  74320. vn = vn.normalize();
  74321. uvs.push(ulength / bounds.width, 0);
  74322. uvs.push(ulength / bounds.width, 1);
  74323. ulength += v3.length();
  74324. uvs.push((ulength / bounds.width), 0);
  74325. uvs.push((ulength / bounds.width), 1);
  74326. if (!flip) {
  74327. normals.push(-vn.x, -vn.y, -vn.z);
  74328. normals.push(-vn.x, -vn.y, -vn.z);
  74329. normals.push(-vn.x, -vn.y, -vn.z);
  74330. normals.push(-vn.x, -vn.y, -vn.z);
  74331. indices.push(StartIndex);
  74332. indices.push(StartIndex + 1);
  74333. indices.push(StartIndex + 2);
  74334. indices.push(StartIndex + 1);
  74335. indices.push(StartIndex + 3);
  74336. indices.push(StartIndex + 2);
  74337. }
  74338. else {
  74339. normals.push(vn.x, vn.y, vn.z);
  74340. normals.push(vn.x, vn.y, vn.z);
  74341. normals.push(vn.x, vn.y, vn.z);
  74342. normals.push(vn.x, vn.y, vn.z);
  74343. indices.push(StartIndex);
  74344. indices.push(StartIndex + 2);
  74345. indices.push(StartIndex + 1);
  74346. indices.push(StartIndex + 1);
  74347. indices.push(StartIndex + 2);
  74348. indices.push(StartIndex + 3);
  74349. }
  74350. StartIndex += 4;
  74351. }
  74352. ;
  74353. };
  74354. return PolygonMeshBuilder;
  74355. }());
  74356. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74357. })(BABYLON || (BABYLON = {}));
  74358. //# sourceMappingURL=babylon.polygonMesh.js.map
  74359. var BABYLON;
  74360. (function (BABYLON) {
  74361. // Unique ID when we import meshes from Babylon to CSG
  74362. var currentCSGMeshId = 0;
  74363. // # class Vertex
  74364. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74365. // one to provide additional features like texture coordinates and vertex
  74366. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74367. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74368. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74369. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74370. // is not used anywhere else.
  74371. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74372. var Vertex = /** @class */ (function () {
  74373. function Vertex(pos, normal, uv) {
  74374. this.pos = pos;
  74375. this.normal = normal;
  74376. this.uv = uv;
  74377. }
  74378. Vertex.prototype.clone = function () {
  74379. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74380. };
  74381. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74382. // orientation of a polygon is flipped.
  74383. Vertex.prototype.flip = function () {
  74384. this.normal = this.normal.scale(-1);
  74385. };
  74386. // Create a new vertex between this vertex and `other` by linearly
  74387. // interpolating all properties using a parameter of `t`. Subclasses should
  74388. // override this to interpolate additional properties.
  74389. Vertex.prototype.interpolate = function (other, t) {
  74390. 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));
  74391. };
  74392. return Vertex;
  74393. }());
  74394. // # class Plane
  74395. // Represents a plane in 3D space.
  74396. var Plane = /** @class */ (function () {
  74397. function Plane(normal, w) {
  74398. this.normal = normal;
  74399. this.w = w;
  74400. }
  74401. Plane.FromPoints = function (a, b, c) {
  74402. var v0 = c.subtract(a);
  74403. var v1 = b.subtract(a);
  74404. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74405. return null;
  74406. }
  74407. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74408. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74409. };
  74410. Plane.prototype.clone = function () {
  74411. return new Plane(this.normal.clone(), this.w);
  74412. };
  74413. Plane.prototype.flip = function () {
  74414. this.normal.scaleInPlace(-1);
  74415. this.w = -this.w;
  74416. };
  74417. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74418. // fragments in the appropriate lists. Coplanar polygons go into either
  74419. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74420. // respect to this plane. Polygons in front or in back of this plane go into
  74421. // either `front` or `back`.
  74422. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74423. var COPLANAR = 0;
  74424. var FRONT = 1;
  74425. var BACK = 2;
  74426. var SPANNING = 3;
  74427. // Classify each point as well as the entire polygon into one of the above
  74428. // four classes.
  74429. var polygonType = 0;
  74430. var types = [];
  74431. var i;
  74432. var t;
  74433. for (i = 0; i < polygon.vertices.length; i++) {
  74434. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74435. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74436. polygonType |= type;
  74437. types.push(type);
  74438. }
  74439. // Put the polygon in the correct list, splitting it when necessary.
  74440. switch (polygonType) {
  74441. case COPLANAR:
  74442. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74443. break;
  74444. case FRONT:
  74445. front.push(polygon);
  74446. break;
  74447. case BACK:
  74448. back.push(polygon);
  74449. break;
  74450. case SPANNING:
  74451. var f = [], b = [];
  74452. for (i = 0; i < polygon.vertices.length; i++) {
  74453. var j = (i + 1) % polygon.vertices.length;
  74454. var ti = types[i], tj = types[j];
  74455. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74456. if (ti !== BACK)
  74457. f.push(vi);
  74458. if (ti !== FRONT)
  74459. b.push(ti !== BACK ? vi.clone() : vi);
  74460. if ((ti | tj) === SPANNING) {
  74461. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74462. var v = vi.interpolate(vj, t);
  74463. f.push(v);
  74464. b.push(v.clone());
  74465. }
  74466. }
  74467. var poly;
  74468. if (f.length >= 3) {
  74469. poly = new Polygon(f, polygon.shared);
  74470. if (poly.plane)
  74471. front.push(poly);
  74472. }
  74473. if (b.length >= 3) {
  74474. poly = new Polygon(b, polygon.shared);
  74475. if (poly.plane)
  74476. back.push(poly);
  74477. }
  74478. break;
  74479. }
  74480. };
  74481. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74482. // point is on the plane.
  74483. Plane.EPSILON = 1e-5;
  74484. return Plane;
  74485. }());
  74486. // # class Polygon
  74487. // Represents a convex polygon. The vertices used to initialize a polygon must
  74488. // be coplanar and form a convex loop.
  74489. //
  74490. // Each convex polygon has a `shared` property, which is shared between all
  74491. // polygons that are clones of each other or were split from the same polygon.
  74492. // This can be used to define per-polygon properties (such as surface color).
  74493. var Polygon = /** @class */ (function () {
  74494. function Polygon(vertices, shared) {
  74495. this.vertices = vertices;
  74496. this.shared = shared;
  74497. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74498. }
  74499. Polygon.prototype.clone = function () {
  74500. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74501. return new Polygon(vertices, this.shared);
  74502. };
  74503. Polygon.prototype.flip = function () {
  74504. this.vertices.reverse().map(function (v) { v.flip(); });
  74505. this.plane.flip();
  74506. };
  74507. return Polygon;
  74508. }());
  74509. // # class Node
  74510. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74511. // by picking a polygon to split along. That polygon (and all other coplanar
  74512. // polygons) are added directly to that node and the other polygons are added to
  74513. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74514. // no distinction between internal and leaf nodes.
  74515. var Node = /** @class */ (function () {
  74516. function Node(polygons) {
  74517. this.plane = null;
  74518. this.front = null;
  74519. this.back = null;
  74520. this.polygons = new Array();
  74521. if (polygons) {
  74522. this.build(polygons);
  74523. }
  74524. }
  74525. Node.prototype.clone = function () {
  74526. var node = new Node();
  74527. node.plane = this.plane && this.plane.clone();
  74528. node.front = this.front && this.front.clone();
  74529. node.back = this.back && this.back.clone();
  74530. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74531. return node;
  74532. };
  74533. // Convert solid space to empty space and empty space to solid space.
  74534. Node.prototype.invert = function () {
  74535. for (var i = 0; i < this.polygons.length; i++) {
  74536. this.polygons[i].flip();
  74537. }
  74538. if (this.plane) {
  74539. this.plane.flip();
  74540. }
  74541. if (this.front) {
  74542. this.front.invert();
  74543. }
  74544. if (this.back) {
  74545. this.back.invert();
  74546. }
  74547. var temp = this.front;
  74548. this.front = this.back;
  74549. this.back = temp;
  74550. };
  74551. // Recursively remove all polygons in `polygons` that are inside this BSP
  74552. // tree.
  74553. Node.prototype.clipPolygons = function (polygons) {
  74554. if (!this.plane)
  74555. return polygons.slice();
  74556. var front = new Array(), back = new Array();
  74557. for (var i = 0; i < polygons.length; i++) {
  74558. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74559. }
  74560. if (this.front) {
  74561. front = this.front.clipPolygons(front);
  74562. }
  74563. if (this.back) {
  74564. back = this.back.clipPolygons(back);
  74565. }
  74566. else {
  74567. back = [];
  74568. }
  74569. return front.concat(back);
  74570. };
  74571. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74572. // `bsp`.
  74573. Node.prototype.clipTo = function (bsp) {
  74574. this.polygons = bsp.clipPolygons(this.polygons);
  74575. if (this.front)
  74576. this.front.clipTo(bsp);
  74577. if (this.back)
  74578. this.back.clipTo(bsp);
  74579. };
  74580. // Return a list of all polygons in this BSP tree.
  74581. Node.prototype.allPolygons = function () {
  74582. var polygons = this.polygons.slice();
  74583. if (this.front)
  74584. polygons = polygons.concat(this.front.allPolygons());
  74585. if (this.back)
  74586. polygons = polygons.concat(this.back.allPolygons());
  74587. return polygons;
  74588. };
  74589. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74590. // new polygons are filtered down to the bottom of the tree and become new
  74591. // nodes there. Each set of polygons is partitioned using the first polygon
  74592. // (no heuristic is used to pick a good split).
  74593. Node.prototype.build = function (polygons) {
  74594. if (!polygons.length)
  74595. return;
  74596. if (!this.plane)
  74597. this.plane = polygons[0].plane.clone();
  74598. var front = new Array(), back = new Array();
  74599. for (var i = 0; i < polygons.length; i++) {
  74600. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74601. }
  74602. if (front.length) {
  74603. if (!this.front)
  74604. this.front = new Node();
  74605. this.front.build(front);
  74606. }
  74607. if (back.length) {
  74608. if (!this.back)
  74609. this.back = new Node();
  74610. this.back.build(back);
  74611. }
  74612. };
  74613. return Node;
  74614. }());
  74615. var CSG = /** @class */ (function () {
  74616. function CSG() {
  74617. this.polygons = new Array();
  74618. }
  74619. // Convert BABYLON.Mesh to BABYLON.CSG
  74620. CSG.FromMesh = function (mesh) {
  74621. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74622. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74623. if (mesh instanceof BABYLON.Mesh) {
  74624. mesh.computeWorldMatrix(true);
  74625. matrix = mesh.getWorldMatrix();
  74626. meshPosition = mesh.position.clone();
  74627. meshRotation = mesh.rotation.clone();
  74628. if (mesh.rotationQuaternion) {
  74629. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74630. }
  74631. meshScaling = mesh.scaling.clone();
  74632. }
  74633. else {
  74634. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74635. }
  74636. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74637. var subMeshes = mesh.subMeshes;
  74638. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74639. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74640. vertices = [];
  74641. for (var j = 0; j < 3; j++) {
  74642. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74643. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74644. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74645. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74646. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74647. vertex = new Vertex(position, normal, uv);
  74648. vertices.push(vertex);
  74649. }
  74650. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74651. // To handle the case of degenerated triangle
  74652. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74653. if (polygon.plane)
  74654. polygons.push(polygon);
  74655. }
  74656. }
  74657. var csg = CSG.FromPolygons(polygons);
  74658. csg.matrix = matrix;
  74659. csg.position = meshPosition;
  74660. csg.rotation = meshRotation;
  74661. csg.scaling = meshScaling;
  74662. csg.rotationQuaternion = meshRotationQuaternion;
  74663. currentCSGMeshId++;
  74664. return csg;
  74665. };
  74666. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74667. CSG.FromPolygons = function (polygons) {
  74668. var csg = new CSG();
  74669. csg.polygons = polygons;
  74670. return csg;
  74671. };
  74672. CSG.prototype.clone = function () {
  74673. var csg = new CSG();
  74674. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74675. csg.copyTransformAttributes(this);
  74676. return csg;
  74677. };
  74678. CSG.prototype.union = function (csg) {
  74679. var a = new Node(this.clone().polygons);
  74680. var b = new Node(csg.clone().polygons);
  74681. a.clipTo(b);
  74682. b.clipTo(a);
  74683. b.invert();
  74684. b.clipTo(a);
  74685. b.invert();
  74686. a.build(b.allPolygons());
  74687. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74688. };
  74689. CSG.prototype.unionInPlace = function (csg) {
  74690. var a = new Node(this.polygons);
  74691. var b = new Node(csg.polygons);
  74692. a.clipTo(b);
  74693. b.clipTo(a);
  74694. b.invert();
  74695. b.clipTo(a);
  74696. b.invert();
  74697. a.build(b.allPolygons());
  74698. this.polygons = a.allPolygons();
  74699. };
  74700. CSG.prototype.subtract = function (csg) {
  74701. var a = new Node(this.clone().polygons);
  74702. var b = new Node(csg.clone().polygons);
  74703. a.invert();
  74704. a.clipTo(b);
  74705. b.clipTo(a);
  74706. b.invert();
  74707. b.clipTo(a);
  74708. b.invert();
  74709. a.build(b.allPolygons());
  74710. a.invert();
  74711. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74712. };
  74713. CSG.prototype.subtractInPlace = function (csg) {
  74714. var a = new Node(this.polygons);
  74715. var b = new Node(csg.polygons);
  74716. a.invert();
  74717. a.clipTo(b);
  74718. b.clipTo(a);
  74719. b.invert();
  74720. b.clipTo(a);
  74721. b.invert();
  74722. a.build(b.allPolygons());
  74723. a.invert();
  74724. this.polygons = a.allPolygons();
  74725. };
  74726. CSG.prototype.intersect = function (csg) {
  74727. var a = new Node(this.clone().polygons);
  74728. var b = new Node(csg.clone().polygons);
  74729. a.invert();
  74730. b.clipTo(a);
  74731. b.invert();
  74732. a.clipTo(b);
  74733. b.clipTo(a);
  74734. a.build(b.allPolygons());
  74735. a.invert();
  74736. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74737. };
  74738. CSG.prototype.intersectInPlace = function (csg) {
  74739. var a = new Node(this.polygons);
  74740. var b = new Node(csg.polygons);
  74741. a.invert();
  74742. b.clipTo(a);
  74743. b.invert();
  74744. a.clipTo(b);
  74745. b.clipTo(a);
  74746. a.build(b.allPolygons());
  74747. a.invert();
  74748. this.polygons = a.allPolygons();
  74749. };
  74750. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74751. // not modified.
  74752. CSG.prototype.inverse = function () {
  74753. var csg = this.clone();
  74754. csg.inverseInPlace();
  74755. return csg;
  74756. };
  74757. CSG.prototype.inverseInPlace = function () {
  74758. this.polygons.map(function (p) { p.flip(); });
  74759. };
  74760. // This is used to keep meshes transformations so they can be restored
  74761. // when we build back a Babylon Mesh
  74762. // NB : All CSG operations are performed in world coordinates
  74763. CSG.prototype.copyTransformAttributes = function (csg) {
  74764. this.matrix = csg.matrix;
  74765. this.position = csg.position;
  74766. this.rotation = csg.rotation;
  74767. this.scaling = csg.scaling;
  74768. this.rotationQuaternion = csg.rotationQuaternion;
  74769. return this;
  74770. };
  74771. // Build Raw mesh from CSG
  74772. // Coordinates here are in world space
  74773. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74774. var matrix = this.matrix.clone();
  74775. matrix.invert();
  74776. 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;
  74777. if (keepSubMeshes) {
  74778. // Sort Polygons, since subMeshes are indices range
  74779. polygons.sort(function (a, b) {
  74780. if (a.shared.meshId === b.shared.meshId) {
  74781. return a.shared.subMeshId - b.shared.subMeshId;
  74782. }
  74783. else {
  74784. return a.shared.meshId - b.shared.meshId;
  74785. }
  74786. });
  74787. }
  74788. for (var i = 0, il = polygons.length; i < il; i++) {
  74789. polygon = polygons[i];
  74790. // Building SubMeshes
  74791. if (!subMesh_dict[polygon.shared.meshId]) {
  74792. subMesh_dict[polygon.shared.meshId] = {};
  74793. }
  74794. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74795. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74796. indexStart: +Infinity,
  74797. indexEnd: -Infinity,
  74798. materialIndex: polygon.shared.materialIndex
  74799. };
  74800. }
  74801. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74802. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74803. polygonIndices[0] = 0;
  74804. polygonIndices[1] = j - 1;
  74805. polygonIndices[2] = j;
  74806. for (var k = 0; k < 3; k++) {
  74807. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74808. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74809. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74810. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74811. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74812. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74813. // Check if 2 points can be merged
  74814. if (!(typeof vertex_idx !== 'undefined' &&
  74815. normals[vertex_idx * 3] === localNormal.x &&
  74816. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74817. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74818. uvs[vertex_idx * 2] === uv.x &&
  74819. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74820. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74821. uvs.push(uv.x, uv.y);
  74822. normals.push(normal.x, normal.y, normal.z);
  74823. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74824. }
  74825. indices.push(vertex_idx);
  74826. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74827. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74828. currentIndex++;
  74829. }
  74830. }
  74831. }
  74832. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74833. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74834. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74835. mesh.setIndices(indices, null);
  74836. if (keepSubMeshes) {
  74837. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74838. var materialIndexOffset = 0, materialMaxIndex;
  74839. mesh.subMeshes = new Array();
  74840. for (var m in subMesh_dict) {
  74841. materialMaxIndex = -1;
  74842. for (var sm in subMesh_dict[m]) {
  74843. subMesh_obj = subMesh_dict[m][sm];
  74844. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74845. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74846. }
  74847. materialIndexOffset += ++materialMaxIndex;
  74848. }
  74849. }
  74850. return mesh;
  74851. };
  74852. // Build Mesh from CSG taking material and transforms into account
  74853. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74854. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74855. mesh.material = material;
  74856. mesh.position.copyFrom(this.position);
  74857. mesh.rotation.copyFrom(this.rotation);
  74858. if (this.rotationQuaternion) {
  74859. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74860. }
  74861. mesh.scaling.copyFrom(this.scaling);
  74862. mesh.computeWorldMatrix(true);
  74863. return mesh;
  74864. };
  74865. return CSG;
  74866. }());
  74867. BABYLON.CSG = CSG;
  74868. })(BABYLON || (BABYLON = {}));
  74869. //# sourceMappingURL=babylon.csg.js.map
  74870. var BABYLON;
  74871. (function (BABYLON) {
  74872. var LensFlare = /** @class */ (function () {
  74873. function LensFlare(size, position, color, imgUrl, system) {
  74874. this.size = size;
  74875. this.position = position;
  74876. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74877. this.color = color || new BABYLON.Color3(1, 1, 1);
  74878. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74879. this._system = system;
  74880. system.lensFlares.push(this);
  74881. }
  74882. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74883. return new LensFlare(size, position, color, imgUrl, system);
  74884. };
  74885. LensFlare.prototype.dispose = function () {
  74886. if (this.texture) {
  74887. this.texture.dispose();
  74888. }
  74889. // Remove from scene
  74890. var index = this._system.lensFlares.indexOf(this);
  74891. this._system.lensFlares.splice(index, 1);
  74892. };
  74893. ;
  74894. return LensFlare;
  74895. }());
  74896. BABYLON.LensFlare = LensFlare;
  74897. })(BABYLON || (BABYLON = {}));
  74898. //# sourceMappingURL=babylon.lensFlare.js.map
  74899. var BABYLON;
  74900. (function (BABYLON) {
  74901. var LensFlareSystem = /** @class */ (function () {
  74902. function LensFlareSystem(name, emitter, scene) {
  74903. this.name = name;
  74904. this.lensFlares = new Array();
  74905. this.borderLimit = 300;
  74906. this.viewportBorder = 0;
  74907. this.layerMask = 0x0FFFFFFF;
  74908. this._vertexBuffers = {};
  74909. this._isEnabled = true;
  74910. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74911. this._emitter = emitter;
  74912. this.id = name;
  74913. scene.lensFlareSystems.push(this);
  74914. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74915. var engine = scene.getEngine();
  74916. // VBO
  74917. var vertices = [];
  74918. vertices.push(1, 1);
  74919. vertices.push(-1, 1);
  74920. vertices.push(-1, -1);
  74921. vertices.push(1, -1);
  74922. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74923. // Indices
  74924. var indices = [];
  74925. indices.push(0);
  74926. indices.push(1);
  74927. indices.push(2);
  74928. indices.push(0);
  74929. indices.push(2);
  74930. indices.push(3);
  74931. this._indexBuffer = engine.createIndexBuffer(indices);
  74932. // Effects
  74933. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74934. }
  74935. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74936. get: function () {
  74937. return this._isEnabled;
  74938. },
  74939. set: function (value) {
  74940. this._isEnabled = value;
  74941. },
  74942. enumerable: true,
  74943. configurable: true
  74944. });
  74945. LensFlareSystem.prototype.getScene = function () {
  74946. return this._scene;
  74947. };
  74948. LensFlareSystem.prototype.getEmitter = function () {
  74949. return this._emitter;
  74950. };
  74951. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74952. this._emitter = newEmitter;
  74953. };
  74954. LensFlareSystem.prototype.getEmitterPosition = function () {
  74955. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74956. };
  74957. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74958. var position = this.getEmitterPosition();
  74959. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74960. this._positionX = position.x;
  74961. this._positionY = position.y;
  74962. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74963. if (this.viewportBorder > 0) {
  74964. globalViewport.x -= this.viewportBorder;
  74965. globalViewport.y -= this.viewportBorder;
  74966. globalViewport.width += this.viewportBorder * 2;
  74967. globalViewport.height += this.viewportBorder * 2;
  74968. position.x += this.viewportBorder;
  74969. position.y += this.viewportBorder;
  74970. this._positionX += this.viewportBorder;
  74971. this._positionY += this.viewportBorder;
  74972. }
  74973. if (position.z > 0) {
  74974. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74975. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74976. return true;
  74977. }
  74978. return true;
  74979. }
  74980. return false;
  74981. };
  74982. LensFlareSystem.prototype._isVisible = function () {
  74983. if (!this._isEnabled || !this._scene.activeCamera) {
  74984. return false;
  74985. }
  74986. var emitterPosition = this.getEmitterPosition();
  74987. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74988. var distance = direction.length();
  74989. direction.normalize();
  74990. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74991. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74992. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74993. };
  74994. LensFlareSystem.prototype.render = function () {
  74995. if (!this._effect.isReady() || !this._scene.activeCamera)
  74996. return false;
  74997. var engine = this._scene.getEngine();
  74998. var viewport = this._scene.activeCamera.viewport;
  74999. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75000. // Position
  75001. if (!this.computeEffectivePosition(globalViewport)) {
  75002. return false;
  75003. }
  75004. // Visibility
  75005. if (!this._isVisible()) {
  75006. return false;
  75007. }
  75008. // Intensity
  75009. var awayX;
  75010. var awayY;
  75011. if (this._positionX < this.borderLimit + globalViewport.x) {
  75012. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75013. }
  75014. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75015. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75016. }
  75017. else {
  75018. awayX = 0;
  75019. }
  75020. if (this._positionY < this.borderLimit + globalViewport.y) {
  75021. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75022. }
  75023. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75024. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75025. }
  75026. else {
  75027. awayY = 0;
  75028. }
  75029. var away = (awayX > awayY) ? awayX : awayY;
  75030. away -= this.viewportBorder;
  75031. if (away > this.borderLimit) {
  75032. away = this.borderLimit;
  75033. }
  75034. var intensity = 1.0 - (away / this.borderLimit);
  75035. if (intensity < 0) {
  75036. return false;
  75037. }
  75038. if (intensity > 1.0) {
  75039. intensity = 1.0;
  75040. }
  75041. if (this.viewportBorder > 0) {
  75042. globalViewport.x += this.viewportBorder;
  75043. globalViewport.y += this.viewportBorder;
  75044. globalViewport.width -= this.viewportBorder * 2;
  75045. globalViewport.height -= this.viewportBorder * 2;
  75046. this._positionX -= this.viewportBorder;
  75047. this._positionY -= this.viewportBorder;
  75048. }
  75049. // Position
  75050. var centerX = globalViewport.x + globalViewport.width / 2;
  75051. var centerY = globalViewport.y + globalViewport.height / 2;
  75052. var distX = centerX - this._positionX;
  75053. var distY = centerY - this._positionY;
  75054. // Effects
  75055. engine.enableEffect(this._effect);
  75056. engine.setState(false);
  75057. engine.setDepthBuffer(false);
  75058. // VBOs
  75059. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75060. // Flares
  75061. for (var index = 0; index < this.lensFlares.length; index++) {
  75062. var flare = this.lensFlares[index];
  75063. engine.setAlphaMode(flare.alphaMode);
  75064. var x = centerX - (distX * flare.position);
  75065. var y = centerY - (distY * flare.position);
  75066. var cw = flare.size;
  75067. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75068. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75069. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75070. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75071. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75072. // Texture
  75073. this._effect.setTexture("textureSampler", flare.texture);
  75074. // Color
  75075. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75076. // Draw order
  75077. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75078. }
  75079. engine.setDepthBuffer(true);
  75080. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75081. return true;
  75082. };
  75083. LensFlareSystem.prototype.dispose = function () {
  75084. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75085. if (vertexBuffer) {
  75086. vertexBuffer.dispose();
  75087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75088. }
  75089. if (this._indexBuffer) {
  75090. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75091. this._indexBuffer = null;
  75092. }
  75093. while (this.lensFlares.length) {
  75094. this.lensFlares[0].dispose();
  75095. }
  75096. // Remove from scene
  75097. var index = this._scene.lensFlareSystems.indexOf(this);
  75098. this._scene.lensFlareSystems.splice(index, 1);
  75099. };
  75100. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75101. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75102. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75103. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75104. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75105. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75106. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75107. var parsedFlare = parsedLensFlareSystem.flares[index];
  75108. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75109. }
  75110. return lensFlareSystem;
  75111. };
  75112. LensFlareSystem.prototype.serialize = function () {
  75113. var serializationObject = {};
  75114. serializationObject.id = this.id;
  75115. serializationObject.name = this.name;
  75116. serializationObject.emitterId = this.getEmitter().id;
  75117. serializationObject.borderLimit = this.borderLimit;
  75118. serializationObject.flares = [];
  75119. for (var index = 0; index < this.lensFlares.length; index++) {
  75120. var flare = this.lensFlares[index];
  75121. serializationObject.flares.push({
  75122. size: flare.size,
  75123. position: flare.position,
  75124. color: flare.color.asArray(),
  75125. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75126. });
  75127. }
  75128. return serializationObject;
  75129. };
  75130. return LensFlareSystem;
  75131. }());
  75132. BABYLON.LensFlareSystem = LensFlareSystem;
  75133. })(BABYLON || (BABYLON = {}));
  75134. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75135. var BABYLON;
  75136. (function (BABYLON) {
  75137. /**
  75138. * This is a holder class for the physics joint created by the physics plugin.
  75139. * It holds a set of functions to control the underlying joint.
  75140. */
  75141. var PhysicsJoint = /** @class */ (function () {
  75142. function PhysicsJoint(type, jointData) {
  75143. this.type = type;
  75144. this.jointData = jointData;
  75145. jointData.nativeParams = jointData.nativeParams || {};
  75146. }
  75147. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75148. get: function () {
  75149. return this._physicsJoint;
  75150. },
  75151. set: function (newJoint) {
  75152. if (this._physicsJoint) {
  75153. //remove from the wolrd
  75154. }
  75155. this._physicsJoint = newJoint;
  75156. },
  75157. enumerable: true,
  75158. configurable: true
  75159. });
  75160. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75161. set: function (physicsPlugin) {
  75162. this._physicsPlugin = physicsPlugin;
  75163. },
  75164. enumerable: true,
  75165. configurable: true
  75166. });
  75167. /**
  75168. * Execute a function that is physics-plugin specific.
  75169. * @param {Function} func the function that will be executed.
  75170. * It accepts two parameters: the physics world and the physics joint.
  75171. */
  75172. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75173. func(this._physicsPlugin.world, this._physicsJoint);
  75174. };
  75175. //TODO check if the native joints are the same
  75176. //Joint Types
  75177. PhysicsJoint.DistanceJoint = 0;
  75178. PhysicsJoint.HingeJoint = 1;
  75179. PhysicsJoint.BallAndSocketJoint = 2;
  75180. PhysicsJoint.WheelJoint = 3;
  75181. PhysicsJoint.SliderJoint = 4;
  75182. //OIMO
  75183. PhysicsJoint.PrismaticJoint = 5;
  75184. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75185. PhysicsJoint.UniversalJoint = 6;
  75186. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75187. //Cannon
  75188. //Similar to a Ball-Joint. Different in params
  75189. PhysicsJoint.PointToPointJoint = 8;
  75190. //Cannon only at the moment
  75191. PhysicsJoint.SpringJoint = 9;
  75192. PhysicsJoint.LockJoint = 10;
  75193. return PhysicsJoint;
  75194. }());
  75195. BABYLON.PhysicsJoint = PhysicsJoint;
  75196. /**
  75197. * A class representing a physics distance joint.
  75198. */
  75199. var DistanceJoint = /** @class */ (function (_super) {
  75200. __extends(DistanceJoint, _super);
  75201. function DistanceJoint(jointData) {
  75202. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75203. }
  75204. /**
  75205. * Update the predefined distance.
  75206. */
  75207. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75208. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75209. };
  75210. return DistanceJoint;
  75211. }(PhysicsJoint));
  75212. BABYLON.DistanceJoint = DistanceJoint;
  75213. var MotorEnabledJoint = /** @class */ (function (_super) {
  75214. __extends(MotorEnabledJoint, _super);
  75215. function MotorEnabledJoint(type, jointData) {
  75216. return _super.call(this, type, jointData) || this;
  75217. }
  75218. /**
  75219. * Set the motor values.
  75220. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75221. * @param {number} force the force to apply
  75222. * @param {number} maxForce max force for this motor.
  75223. */
  75224. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75225. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75226. };
  75227. /**
  75228. * Set the motor's limits.
  75229. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75230. */
  75231. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75232. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75233. };
  75234. return MotorEnabledJoint;
  75235. }(PhysicsJoint));
  75236. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75237. /**
  75238. * This class represents a single hinge physics joint
  75239. */
  75240. var HingeJoint = /** @class */ (function (_super) {
  75241. __extends(HingeJoint, _super);
  75242. function HingeJoint(jointData) {
  75243. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75244. }
  75245. /**
  75246. * Set the motor values.
  75247. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75248. * @param {number} force the force to apply
  75249. * @param {number} maxForce max force for this motor.
  75250. */
  75251. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75252. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75253. };
  75254. /**
  75255. * Set the motor's limits.
  75256. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75257. */
  75258. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75259. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75260. };
  75261. return HingeJoint;
  75262. }(MotorEnabledJoint));
  75263. BABYLON.HingeJoint = HingeJoint;
  75264. /**
  75265. * This class represents a dual hinge physics joint (same as wheel joint)
  75266. */
  75267. var Hinge2Joint = /** @class */ (function (_super) {
  75268. __extends(Hinge2Joint, _super);
  75269. function Hinge2Joint(jointData) {
  75270. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75271. }
  75272. /**
  75273. * Set the motor values.
  75274. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75275. * @param {number} force the force to apply
  75276. * @param {number} maxForce max force for this motor.
  75277. * @param {motorIndex} the motor's index, 0 or 1.
  75278. */
  75279. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75280. if (motorIndex === void 0) { motorIndex = 0; }
  75281. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75282. };
  75283. /**
  75284. * Set the motor limits.
  75285. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75286. * @param {number} upperLimit the upper limit
  75287. * @param {number} lowerLimit lower limit
  75288. * @param {motorIndex} the motor's index, 0 or 1.
  75289. */
  75290. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75291. if (motorIndex === void 0) { motorIndex = 0; }
  75292. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75293. };
  75294. return Hinge2Joint;
  75295. }(MotorEnabledJoint));
  75296. BABYLON.Hinge2Joint = Hinge2Joint;
  75297. })(BABYLON || (BABYLON = {}));
  75298. //# sourceMappingURL=babylon.physicsJoint.js.map
  75299. var BABYLON;
  75300. (function (BABYLON) {
  75301. var PhysicsImpostor = /** @class */ (function () {
  75302. function PhysicsImpostor(object, type, _options, _scene) {
  75303. if (_options === void 0) { _options = { mass: 0 }; }
  75304. var _this = this;
  75305. this.object = object;
  75306. this.type = type;
  75307. this._options = _options;
  75308. this._scene = _scene;
  75309. this._bodyUpdateRequired = false;
  75310. this._onBeforePhysicsStepCallbacks = new Array();
  75311. this._onAfterPhysicsStepCallbacks = new Array();
  75312. this._onPhysicsCollideCallbacks = [];
  75313. this._deltaPosition = BABYLON.Vector3.Zero();
  75314. this._isDisposed = false;
  75315. //temp variables for parent rotation calculations
  75316. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75317. this._tmpQuat = new BABYLON.Quaternion();
  75318. this._tmpQuat2 = new BABYLON.Quaternion();
  75319. /**
  75320. * this function is executed by the physics engine.
  75321. */
  75322. this.beforeStep = function () {
  75323. if (!_this._physicsEngine) {
  75324. return;
  75325. }
  75326. _this.object.translate(_this._deltaPosition, -1);
  75327. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75328. _this.object.computeWorldMatrix(false);
  75329. if (_this.object.parent && _this.object.rotationQuaternion) {
  75330. _this.getParentsRotation();
  75331. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75332. }
  75333. else {
  75334. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75335. }
  75336. if (!_this._options.disableBidirectionalTransformation) {
  75337. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75338. }
  75339. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75340. func(_this);
  75341. });
  75342. };
  75343. /**
  75344. * this function is executed by the physics engine.
  75345. */
  75346. this.afterStep = function () {
  75347. if (!_this._physicsEngine) {
  75348. return;
  75349. }
  75350. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75351. func(_this);
  75352. });
  75353. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75354. // object has now its world rotation. needs to be converted to local.
  75355. if (_this.object.parent && _this.object.rotationQuaternion) {
  75356. _this.getParentsRotation();
  75357. _this._tmpQuat.conjugateInPlace();
  75358. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75359. }
  75360. // take the position set and make it the absolute position of this object.
  75361. _this.object.setAbsolutePosition(_this.object.position);
  75362. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75363. _this.object.translate(_this._deltaPosition, 1);
  75364. };
  75365. /**
  75366. * Legacy collision detection event support
  75367. */
  75368. this.onCollideEvent = null;
  75369. //event and body object due to cannon's event-based architecture.
  75370. this.onCollide = function (e) {
  75371. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75372. return;
  75373. }
  75374. if (!_this._physicsEngine) {
  75375. return;
  75376. }
  75377. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75378. if (otherImpostor) {
  75379. // Legacy collision detection event support
  75380. if (_this.onCollideEvent) {
  75381. _this.onCollideEvent(_this, otherImpostor);
  75382. }
  75383. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75384. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75385. }).forEach(function (obj) {
  75386. obj.callback(_this, otherImpostor);
  75387. });
  75388. }
  75389. };
  75390. //sanity check!
  75391. if (!this.object) {
  75392. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75393. return;
  75394. }
  75395. //legacy support for old syntax.
  75396. if (!this._scene && object.getScene) {
  75397. this._scene = object.getScene();
  75398. }
  75399. if (!this._scene) {
  75400. return;
  75401. }
  75402. this._physicsEngine = this._scene.getPhysicsEngine();
  75403. if (!this._physicsEngine) {
  75404. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75405. }
  75406. else {
  75407. //set the object's quaternion, if not set
  75408. if (!this.object.rotationQuaternion) {
  75409. if (this.object.rotation) {
  75410. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75411. }
  75412. else {
  75413. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75414. }
  75415. }
  75416. //default options params
  75417. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75418. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75419. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75420. this._joints = [];
  75421. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75422. if (!this.object.parent || this._options.ignoreParent) {
  75423. this._init();
  75424. }
  75425. else if (this.object.parent.physicsImpostor) {
  75426. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75427. }
  75428. }
  75429. }
  75430. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75431. get: function () {
  75432. return this._isDisposed;
  75433. },
  75434. enumerable: true,
  75435. configurable: true
  75436. });
  75437. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75438. get: function () {
  75439. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75440. },
  75441. set: function (value) {
  75442. this.setMass(value);
  75443. },
  75444. enumerable: true,
  75445. configurable: true
  75446. });
  75447. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75448. get: function () {
  75449. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75450. },
  75451. set: function (value) {
  75452. if (!this._physicsEngine) {
  75453. return;
  75454. }
  75455. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75456. },
  75457. enumerable: true,
  75458. configurable: true
  75459. });
  75460. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75461. get: function () {
  75462. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75463. },
  75464. set: function (value) {
  75465. if (!this._physicsEngine) {
  75466. return;
  75467. }
  75468. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75469. },
  75470. enumerable: true,
  75471. configurable: true
  75472. });
  75473. /**
  75474. * This function will completly initialize this impostor.
  75475. * It will create a new body - but only if this mesh has no parent.
  75476. * If it has, this impostor will not be used other than to define the impostor
  75477. * of the child mesh.
  75478. */
  75479. PhysicsImpostor.prototype._init = function () {
  75480. if (!this._physicsEngine) {
  75481. return;
  75482. }
  75483. this._physicsEngine.removeImpostor(this);
  75484. this.physicsBody = null;
  75485. this._parent = this._parent || this._getPhysicsParent();
  75486. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75487. this._physicsEngine.addImpostor(this);
  75488. }
  75489. };
  75490. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75491. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75492. var parentMesh = this.object.parent;
  75493. return parentMesh.physicsImpostor;
  75494. }
  75495. return null;
  75496. };
  75497. /**
  75498. * Should a new body be generated.
  75499. */
  75500. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75501. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75502. };
  75503. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75504. this.forceUpdate();
  75505. };
  75506. /**
  75507. * Force a regeneration of this or the parent's impostor's body.
  75508. * Use under cautious - This will remove all joints already implemented.
  75509. */
  75510. PhysicsImpostor.prototype.forceUpdate = function () {
  75511. this._init();
  75512. if (this.parent && !this._options.ignoreParent) {
  75513. this.parent.forceUpdate();
  75514. }
  75515. };
  75516. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75517. /*public get mesh(): AbstractMesh {
  75518. return this._mesh;
  75519. }*/
  75520. /**
  75521. * Gets the body that holds this impostor. Either its own, or its parent.
  75522. */
  75523. get: function () {
  75524. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75525. },
  75526. /**
  75527. * Set the physics body. Used mainly by the physics engine/plugin
  75528. */
  75529. set: function (physicsBody) {
  75530. if (this._physicsBody && this._physicsEngine) {
  75531. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75532. }
  75533. this._physicsBody = physicsBody;
  75534. this.resetUpdateFlags();
  75535. },
  75536. enumerable: true,
  75537. configurable: true
  75538. });
  75539. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75540. get: function () {
  75541. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75542. },
  75543. set: function (value) {
  75544. this._parent = value;
  75545. },
  75546. enumerable: true,
  75547. configurable: true
  75548. });
  75549. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75550. this._bodyUpdateRequired = false;
  75551. };
  75552. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75553. if (this.object.getBoundingInfo) {
  75554. var q = this.object.rotationQuaternion;
  75555. //reset rotation
  75556. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75557. //calculate the world matrix with no rotation
  75558. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75559. var boundingInfo = this.object.getBoundingInfo();
  75560. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75561. //bring back the rotation
  75562. this.object.rotationQuaternion = q;
  75563. //calculate the world matrix with the new rotation
  75564. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75565. return size;
  75566. }
  75567. else {
  75568. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75569. }
  75570. };
  75571. PhysicsImpostor.prototype.getObjectCenter = function () {
  75572. if (this.object.getBoundingInfo) {
  75573. var boundingInfo = this.object.getBoundingInfo();
  75574. return boundingInfo.boundingBox.centerWorld;
  75575. }
  75576. else {
  75577. return this.object.position;
  75578. }
  75579. };
  75580. /**
  75581. * Get a specific parametes from the options parameter.
  75582. */
  75583. PhysicsImpostor.prototype.getParam = function (paramName) {
  75584. return this._options[paramName];
  75585. };
  75586. /**
  75587. * Sets a specific parameter in the options given to the physics plugin
  75588. */
  75589. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75590. this._options[paramName] = value;
  75591. this._bodyUpdateRequired = true;
  75592. };
  75593. /**
  75594. * Specifically change the body's mass option. Won't recreate the physics body object
  75595. */
  75596. PhysicsImpostor.prototype.setMass = function (mass) {
  75597. if (this.getParam("mass") !== mass) {
  75598. this.setParam("mass", mass);
  75599. }
  75600. if (this._physicsEngine) {
  75601. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75602. }
  75603. };
  75604. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75605. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75606. };
  75607. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75608. if (this._physicsEngine) {
  75609. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75610. }
  75611. };
  75612. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75613. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75614. };
  75615. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75616. if (this._physicsEngine) {
  75617. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75618. }
  75619. };
  75620. /**
  75621. * Execute a function with the physics plugin native code.
  75622. * Provide a function the will have two variables - the world object and the physics body object.
  75623. */
  75624. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75625. if (this._physicsEngine) {
  75626. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75627. }
  75628. };
  75629. /**
  75630. * Register a function that will be executed before the physics world is stepping forward.
  75631. */
  75632. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75633. this._onBeforePhysicsStepCallbacks.push(func);
  75634. };
  75635. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75636. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75637. if (index > -1) {
  75638. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75639. }
  75640. else {
  75641. BABYLON.Tools.Warn("Function to remove was not found");
  75642. }
  75643. };
  75644. /**
  75645. * Register a function that will be executed after the physics step
  75646. */
  75647. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75648. this._onAfterPhysicsStepCallbacks.push(func);
  75649. };
  75650. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75651. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75652. if (index > -1) {
  75653. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75654. }
  75655. else {
  75656. BABYLON.Tools.Warn("Function to remove was not found");
  75657. }
  75658. };
  75659. /**
  75660. * register a function that will be executed when this impostor collides against a different body.
  75661. */
  75662. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75663. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75664. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75665. };
  75666. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75667. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75668. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75669. if (index > -1) {
  75670. this._onPhysicsCollideCallbacks.splice(index, 1);
  75671. }
  75672. else {
  75673. BABYLON.Tools.Warn("Function to remove was not found");
  75674. }
  75675. };
  75676. PhysicsImpostor.prototype.getParentsRotation = function () {
  75677. var parent = this.object.parent;
  75678. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75679. while (parent) {
  75680. if (parent.rotationQuaternion) {
  75681. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75682. }
  75683. else {
  75684. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75685. }
  75686. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75687. parent = parent.parent;
  75688. }
  75689. return this._tmpQuat;
  75690. };
  75691. /**
  75692. * Apply a force
  75693. */
  75694. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75695. if (this._physicsEngine) {
  75696. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75697. }
  75698. return this;
  75699. };
  75700. /**
  75701. * Apply an impulse
  75702. */
  75703. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75704. if (this._physicsEngine) {
  75705. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75706. }
  75707. return this;
  75708. };
  75709. /**
  75710. * A help function to create a joint.
  75711. */
  75712. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75713. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75714. this.addJoint(otherImpostor, joint);
  75715. return this;
  75716. };
  75717. /**
  75718. * Add a joint to this impostor with a different impostor.
  75719. */
  75720. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75721. this._joints.push({
  75722. otherImpostor: otherImpostor,
  75723. joint: joint
  75724. });
  75725. if (this._physicsEngine) {
  75726. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75727. }
  75728. return this;
  75729. };
  75730. /**
  75731. * Will keep this body still, in a sleep mode.
  75732. */
  75733. PhysicsImpostor.prototype.sleep = function () {
  75734. if (this._physicsEngine) {
  75735. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75736. }
  75737. return this;
  75738. };
  75739. /**
  75740. * Wake the body up.
  75741. */
  75742. PhysicsImpostor.prototype.wakeUp = function () {
  75743. if (this._physicsEngine) {
  75744. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75745. }
  75746. return this;
  75747. };
  75748. PhysicsImpostor.prototype.clone = function (newObject) {
  75749. if (!newObject)
  75750. return null;
  75751. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75752. };
  75753. PhysicsImpostor.prototype.dispose = function () {
  75754. var _this = this;
  75755. //no dispose if no physics engine is available.
  75756. if (!this._physicsEngine) {
  75757. return;
  75758. }
  75759. this._joints.forEach(function (j) {
  75760. if (_this._physicsEngine) {
  75761. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75762. }
  75763. });
  75764. //dispose the physics body
  75765. this._physicsEngine.removeImpostor(this);
  75766. if (this.parent) {
  75767. this.parent.forceUpdate();
  75768. }
  75769. else {
  75770. /*this._object.getChildMeshes().forEach(function(mesh) {
  75771. if (mesh.physicsImpostor) {
  75772. if (disposeChildren) {
  75773. mesh.physicsImpostor.dispose();
  75774. mesh.physicsImpostor = null;
  75775. }
  75776. }
  75777. })*/
  75778. }
  75779. this._isDisposed = true;
  75780. };
  75781. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75782. this._deltaPosition.copyFrom(position);
  75783. };
  75784. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75785. if (!this._deltaRotation) {
  75786. this._deltaRotation = new BABYLON.Quaternion();
  75787. }
  75788. this._deltaRotation.copyFrom(rotation);
  75789. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75790. };
  75791. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75792. if (this._physicsEngine) {
  75793. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75794. }
  75795. return this;
  75796. };
  75797. PhysicsImpostor.prototype.getRadius = function () {
  75798. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75799. };
  75800. /**
  75801. * Sync a bone with this impostor
  75802. * @param bone The bone to sync to the impostor.
  75803. * @param boneMesh The mesh that the bone is influencing.
  75804. * @param jointPivot The pivot of the joint / bone in local space.
  75805. * @param distToJoint Optional distance from the impostor to the joint.
  75806. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75807. */
  75808. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75809. var tempVec = PhysicsImpostor._tmpVecs[0];
  75810. var mesh = this.object;
  75811. if (mesh.rotationQuaternion) {
  75812. if (adjustRotation) {
  75813. var tempQuat = PhysicsImpostor._tmpQuat;
  75814. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75815. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75816. }
  75817. else {
  75818. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75819. }
  75820. }
  75821. tempVec.x = 0;
  75822. tempVec.y = 0;
  75823. tempVec.z = 0;
  75824. if (jointPivot) {
  75825. tempVec.x = jointPivot.x;
  75826. tempVec.y = jointPivot.y;
  75827. tempVec.z = jointPivot.z;
  75828. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75829. if (distToJoint === undefined || distToJoint === null) {
  75830. distToJoint = jointPivot.length();
  75831. }
  75832. tempVec.x *= distToJoint;
  75833. tempVec.y *= distToJoint;
  75834. tempVec.z *= distToJoint;
  75835. }
  75836. if (bone.getParent()) {
  75837. tempVec.addInPlace(mesh.getAbsolutePosition());
  75838. bone.setAbsolutePosition(tempVec, boneMesh);
  75839. }
  75840. else {
  75841. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75842. boneMesh.position.x -= tempVec.x;
  75843. boneMesh.position.y -= tempVec.y;
  75844. boneMesh.position.z -= tempVec.z;
  75845. }
  75846. };
  75847. /**
  75848. * Sync impostor to a bone
  75849. * @param bone The bone that the impostor will be synced to.
  75850. * @param boneMesh The mesh that the bone is influencing.
  75851. * @param jointPivot The pivot of the joint / bone in local space.
  75852. * @param distToJoint Optional distance from the impostor to the joint.
  75853. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75854. * @param boneAxis Optional vector3 axis the bone is aligned with
  75855. */
  75856. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75857. var mesh = this.object;
  75858. if (mesh.rotationQuaternion) {
  75859. if (adjustRotation) {
  75860. var tempQuat = PhysicsImpostor._tmpQuat;
  75861. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75862. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75863. }
  75864. else {
  75865. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75866. }
  75867. }
  75868. var pos = PhysicsImpostor._tmpVecs[0];
  75869. var boneDir = PhysicsImpostor._tmpVecs[1];
  75870. if (!boneAxis) {
  75871. boneAxis = PhysicsImpostor._tmpVecs[2];
  75872. boneAxis.x = 0;
  75873. boneAxis.y = 1;
  75874. boneAxis.z = 0;
  75875. }
  75876. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75877. bone.getAbsolutePositionToRef(boneMesh, pos);
  75878. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75879. distToJoint = jointPivot.length();
  75880. }
  75881. if (distToJoint !== undefined && distToJoint !== null) {
  75882. pos.x += boneDir.x * distToJoint;
  75883. pos.y += boneDir.y * distToJoint;
  75884. pos.z += boneDir.z * distToJoint;
  75885. }
  75886. mesh.setAbsolutePosition(pos);
  75887. };
  75888. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75889. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75890. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75891. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75892. //Impostor types
  75893. PhysicsImpostor.NoImpostor = 0;
  75894. PhysicsImpostor.SphereImpostor = 1;
  75895. PhysicsImpostor.BoxImpostor = 2;
  75896. PhysicsImpostor.PlaneImpostor = 3;
  75897. PhysicsImpostor.MeshImpostor = 4;
  75898. PhysicsImpostor.CylinderImpostor = 7;
  75899. PhysicsImpostor.ParticleImpostor = 8;
  75900. PhysicsImpostor.HeightmapImpostor = 9;
  75901. return PhysicsImpostor;
  75902. }());
  75903. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75904. })(BABYLON || (BABYLON = {}));
  75905. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75906. var BABYLON;
  75907. (function (BABYLON) {
  75908. var PhysicsEngine = /** @class */ (function () {
  75909. function PhysicsEngine(gravity, _physicsPlugin) {
  75910. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75911. this._physicsPlugin = _physicsPlugin;
  75912. //new methods and parameters
  75913. this._impostors = [];
  75914. this._joints = [];
  75915. if (!this._physicsPlugin.isSupported()) {
  75916. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75917. + "Please make sure it is included.");
  75918. }
  75919. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75920. this.setGravity(gravity);
  75921. this.setTimeStep();
  75922. }
  75923. PhysicsEngine.prototype.setGravity = function (gravity) {
  75924. this.gravity = gravity;
  75925. this._physicsPlugin.setGravity(this.gravity);
  75926. };
  75927. /**
  75928. * Set the time step of the physics engine.
  75929. * default is 1/60.
  75930. * To slow it down, enter 1/600 for example.
  75931. * To speed it up, 1/30
  75932. * @param {number} newTimeStep the new timestep to apply to this world.
  75933. */
  75934. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75935. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75936. this._physicsPlugin.setTimeStep(newTimeStep);
  75937. };
  75938. /**
  75939. * Get the time step of the physics engine.
  75940. */
  75941. PhysicsEngine.prototype.getTimeStep = function () {
  75942. return this._physicsPlugin.getTimeStep();
  75943. };
  75944. PhysicsEngine.prototype.dispose = function () {
  75945. this._impostors.forEach(function (impostor) {
  75946. impostor.dispose();
  75947. });
  75948. this._physicsPlugin.dispose();
  75949. };
  75950. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75951. return this._physicsPlugin.name;
  75952. };
  75953. /**
  75954. * Adding a new impostor for the impostor tracking.
  75955. * This will be done by the impostor itself.
  75956. * @param {PhysicsImpostor} impostor the impostor to add
  75957. */
  75958. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75959. impostor.uniqueId = this._impostors.push(impostor);
  75960. //if no parent, generate the body
  75961. if (!impostor.parent) {
  75962. this._physicsPlugin.generatePhysicsBody(impostor);
  75963. }
  75964. };
  75965. /**
  75966. * Remove an impostor from the engine.
  75967. * This impostor and its mesh will not longer be updated by the physics engine.
  75968. * @param {PhysicsImpostor} impostor the impostor to remove
  75969. */
  75970. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75971. var index = this._impostors.indexOf(impostor);
  75972. if (index > -1) {
  75973. var removed = this._impostors.splice(index, 1);
  75974. //Is it needed?
  75975. if (removed.length) {
  75976. //this will also remove it from the world.
  75977. removed[0].physicsBody = null;
  75978. }
  75979. }
  75980. };
  75981. /**
  75982. * Add a joint to the physics engine
  75983. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75984. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75985. * @param {PhysicsJoint} the joint that will connect both impostors.
  75986. */
  75987. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75988. var impostorJoint = {
  75989. mainImpostor: mainImpostor,
  75990. connectedImpostor: connectedImpostor,
  75991. joint: joint
  75992. };
  75993. joint.physicsPlugin = this._physicsPlugin;
  75994. this._joints.push(impostorJoint);
  75995. this._physicsPlugin.generateJoint(impostorJoint);
  75996. };
  75997. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75998. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75999. return (impostorJoint.connectedImpostor === connectedImpostor
  76000. && impostorJoint.joint === joint
  76001. && impostorJoint.mainImpostor === mainImpostor);
  76002. });
  76003. if (matchingJoints.length) {
  76004. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76005. //TODO remove it from the list as well
  76006. }
  76007. };
  76008. /**
  76009. * Called by the scene. no need to call it.
  76010. */
  76011. PhysicsEngine.prototype._step = function (delta) {
  76012. var _this = this;
  76013. //check if any mesh has no body / requires an update
  76014. this._impostors.forEach(function (impostor) {
  76015. if (impostor.isBodyInitRequired()) {
  76016. _this._physicsPlugin.generatePhysicsBody(impostor);
  76017. }
  76018. });
  76019. if (delta > 0.1) {
  76020. delta = 0.1;
  76021. }
  76022. else if (delta <= 0) {
  76023. delta = 1.0 / 60.0;
  76024. }
  76025. this._physicsPlugin.executeStep(delta, this._impostors);
  76026. };
  76027. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76028. return this._physicsPlugin;
  76029. };
  76030. PhysicsEngine.prototype.getImpostors = function () {
  76031. return this._impostors;
  76032. };
  76033. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76034. for (var i = 0; i < this._impostors.length; ++i) {
  76035. if (this._impostors[i].object === object) {
  76036. return this._impostors[i];
  76037. }
  76038. }
  76039. return null;
  76040. };
  76041. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76042. for (var i = 0; i < this._impostors.length; ++i) {
  76043. if (this._impostors[i].physicsBody === body) {
  76044. return this._impostors[i];
  76045. }
  76046. }
  76047. return null;
  76048. };
  76049. // Statics
  76050. PhysicsEngine.Epsilon = 0.001;
  76051. return PhysicsEngine;
  76052. }());
  76053. BABYLON.PhysicsEngine = PhysicsEngine;
  76054. })(BABYLON || (BABYLON = {}));
  76055. //# sourceMappingURL=babylon.physicsEngine.js.map
  76056. var BABYLON;
  76057. (function (BABYLON) {
  76058. var PhysicsHelper = /** @class */ (function () {
  76059. function PhysicsHelper(scene) {
  76060. this._scene = scene;
  76061. this._physicsEngine = this._scene.getPhysicsEngine();
  76062. if (!this._physicsEngine) {
  76063. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76064. }
  76065. }
  76066. /**
  76067. * @param {Vector3} origin the origin of the explosion
  76068. * @param {number} radius the explosion radius
  76069. * @param {number} strength the explosion strength
  76070. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76071. */
  76072. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76073. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76074. if (!this._physicsEngine) {
  76075. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76076. return null;
  76077. }
  76078. var impostors = this._physicsEngine.getImpostors();
  76079. if (impostors.length === 0) {
  76080. return null;
  76081. }
  76082. var event = new PhysicsRadialExplosionEvent(this._scene);
  76083. impostors.forEach(function (impostor) {
  76084. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76085. if (!impostorForceAndContactPoint) {
  76086. return;
  76087. }
  76088. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76089. });
  76090. event.dispose(false);
  76091. return event;
  76092. };
  76093. /**
  76094. * @param {Vector3} origin the origin of the explosion
  76095. * @param {number} radius the explosion radius
  76096. * @param {number} strength the explosion strength
  76097. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76098. */
  76099. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76100. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76101. if (!this._physicsEngine) {
  76102. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76103. return null;
  76104. }
  76105. var impostors = this._physicsEngine.getImpostors();
  76106. if (impostors.length === 0) {
  76107. return null;
  76108. }
  76109. var event = new PhysicsRadialExplosionEvent(this._scene);
  76110. impostors.forEach(function (impostor) {
  76111. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76112. if (!impostorForceAndContactPoint) {
  76113. return;
  76114. }
  76115. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76116. });
  76117. event.dispose(false);
  76118. return event;
  76119. };
  76120. /**
  76121. * @param {Vector3} origin the origin of the explosion
  76122. * @param {number} radius the explosion radius
  76123. * @param {number} strength the explosion strength
  76124. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76125. */
  76126. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76127. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76128. if (!this._physicsEngine) {
  76129. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76130. return null;
  76131. }
  76132. var impostors = this._physicsEngine.getImpostors();
  76133. if (impostors.length === 0) {
  76134. return null;
  76135. }
  76136. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76137. event.dispose(false);
  76138. return event;
  76139. };
  76140. /**
  76141. * @param {Vector3} origin the origin of the updraft
  76142. * @param {number} radius the radius of the updraft
  76143. * @param {number} strength the strength of the updraft
  76144. * @param {number} height the height of the updraft
  76145. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76146. */
  76147. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76148. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76149. if (!this._physicsEngine) {
  76150. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76151. return null;
  76152. }
  76153. if (this._physicsEngine.getImpostors().length === 0) {
  76154. return null;
  76155. }
  76156. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76157. event.dispose(false);
  76158. return event;
  76159. };
  76160. /**
  76161. * @param {Vector3} origin the of the vortex
  76162. * @param {number} radius the radius of the vortex
  76163. * @param {number} strength the strength of the vortex
  76164. * @param {number} height the height of the vortex
  76165. */
  76166. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76167. if (!this._physicsEngine) {
  76168. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76169. return null;
  76170. }
  76171. if (this._physicsEngine.getImpostors().length === 0) {
  76172. return null;
  76173. }
  76174. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76175. event.dispose(false);
  76176. return event;
  76177. };
  76178. return PhysicsHelper;
  76179. }());
  76180. BABYLON.PhysicsHelper = PhysicsHelper;
  76181. /***** Radial explosion *****/
  76182. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76183. function PhysicsRadialExplosionEvent(scene) {
  76184. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76185. this._rays = [];
  76186. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76187. this._scene = scene;
  76188. }
  76189. /**
  76190. * Returns the data related to the radial explosion event (sphere & rays).
  76191. * @returns {PhysicsRadialExplosionEventData}
  76192. */
  76193. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76194. this._dataFetched = true;
  76195. return {
  76196. sphere: this._sphere,
  76197. rays: this._rays,
  76198. };
  76199. };
  76200. /**
  76201. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76202. * @param impostor
  76203. * @param {Vector3} origin the origin of the explosion
  76204. * @param {number} radius the explosion radius
  76205. * @param {number} strength the explosion strength
  76206. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76207. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76208. */
  76209. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76210. if (impostor.mass === 0) {
  76211. return null;
  76212. }
  76213. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76214. return null;
  76215. }
  76216. if (impostor.object.getClassName() !== 'Mesh') {
  76217. return null;
  76218. }
  76219. var impostorObject = impostor.object;
  76220. var impostorObjectCenter = impostor.getObjectCenter();
  76221. var direction = impostorObjectCenter.subtract(origin);
  76222. var ray = new BABYLON.Ray(origin, direction, radius);
  76223. this._rays.push(ray);
  76224. var hit = ray.intersectsMesh(impostorObject);
  76225. var contactPoint = hit.pickedPoint;
  76226. if (!contactPoint) {
  76227. return null;
  76228. }
  76229. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76230. if (distanceFromOrigin > radius) {
  76231. return null;
  76232. }
  76233. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76234. ? strength
  76235. : strength * (1 - (distanceFromOrigin / radius));
  76236. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76237. return { force: force, contactPoint: contactPoint };
  76238. };
  76239. /**
  76240. * Disposes the sphere.
  76241. * @param {bolean} force
  76242. */
  76243. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76244. var _this = this;
  76245. if (force === void 0) { force = true; }
  76246. if (force) {
  76247. this._sphere.dispose();
  76248. }
  76249. else {
  76250. setTimeout(function () {
  76251. if (!_this._dataFetched) {
  76252. _this._sphere.dispose();
  76253. }
  76254. }, 0);
  76255. }
  76256. };
  76257. /*** Helpers ***/
  76258. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76259. if (!this._sphere) {
  76260. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76261. this._sphere.isVisible = false;
  76262. }
  76263. };
  76264. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76265. var impostorObject = impostor.object;
  76266. this._prepareSphere();
  76267. this._sphere.position = origin;
  76268. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76269. this._sphere._updateBoundingInfo();
  76270. this._sphere.computeWorldMatrix(true);
  76271. return this._sphere.intersectsMesh(impostorObject, true);
  76272. };
  76273. return PhysicsRadialExplosionEvent;
  76274. }());
  76275. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76276. /***** Gravitational Field *****/
  76277. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76278. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76279. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76280. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76281. this._physicsHelper = physicsHelper;
  76282. this._scene = scene;
  76283. this._origin = origin;
  76284. this._radius = radius;
  76285. this._strength = strength;
  76286. this._falloff = falloff;
  76287. this._tickCallback = this._tick.bind(this);
  76288. }
  76289. /**
  76290. * Returns the data related to the gravitational field event (sphere).
  76291. * @returns {PhysicsGravitationalFieldEventData}
  76292. */
  76293. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76294. this._dataFetched = true;
  76295. return {
  76296. sphere: this._sphere,
  76297. };
  76298. };
  76299. /**
  76300. * Enables the gravitational field.
  76301. */
  76302. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76303. this._tickCallback.call(this);
  76304. this._scene.registerBeforeRender(this._tickCallback);
  76305. };
  76306. /**
  76307. * Disables the gravitational field.
  76308. */
  76309. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76310. this._scene.unregisterBeforeRender(this._tickCallback);
  76311. };
  76312. /**
  76313. * Disposes the sphere.
  76314. * @param {bolean} force
  76315. */
  76316. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76317. var _this = this;
  76318. if (force === void 0) { force = true; }
  76319. if (force) {
  76320. this._sphere.dispose();
  76321. }
  76322. else {
  76323. setTimeout(function () {
  76324. if (!_this._dataFetched) {
  76325. _this._sphere.dispose();
  76326. }
  76327. }, 0);
  76328. }
  76329. };
  76330. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76331. // Since the params won't change, we fetch the event only once
  76332. if (this._sphere) {
  76333. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76334. }
  76335. else {
  76336. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76337. if (radialExplosionEvent) {
  76338. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76339. }
  76340. }
  76341. };
  76342. return PhysicsGravitationalFieldEvent;
  76343. }());
  76344. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76345. /***** Updraft *****/
  76346. var PhysicsUpdraftEvent = /** @class */ (function () {
  76347. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76348. this._scene = _scene;
  76349. this._origin = _origin;
  76350. this._radius = _radius;
  76351. this._strength = _strength;
  76352. this._height = _height;
  76353. this._updraftMode = _updraftMode;
  76354. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76355. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76356. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76357. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76358. this._physicsEngine = this._scene.getPhysicsEngine();
  76359. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76360. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76361. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76362. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76363. }
  76364. this._tickCallback = this._tick.bind(this);
  76365. }
  76366. /**
  76367. * Returns the data related to the updraft event (cylinder).
  76368. * @returns {PhysicsUpdraftEventData}
  76369. */
  76370. PhysicsUpdraftEvent.prototype.getData = function () {
  76371. this._dataFetched = true;
  76372. return {
  76373. cylinder: this._cylinder,
  76374. };
  76375. };
  76376. /**
  76377. * Enables the updraft.
  76378. */
  76379. PhysicsUpdraftEvent.prototype.enable = function () {
  76380. this._tickCallback.call(this);
  76381. this._scene.registerBeforeRender(this._tickCallback);
  76382. };
  76383. /**
  76384. * Disables the cortex.
  76385. */
  76386. PhysicsUpdraftEvent.prototype.disable = function () {
  76387. this._scene.unregisterBeforeRender(this._tickCallback);
  76388. };
  76389. /**
  76390. * Disposes the sphere.
  76391. * @param {bolean} force
  76392. */
  76393. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76394. var _this = this;
  76395. if (force === void 0) { force = true; }
  76396. if (force) {
  76397. this._cylinder.dispose();
  76398. }
  76399. else {
  76400. setTimeout(function () {
  76401. if (!_this._dataFetched) {
  76402. _this._cylinder.dispose();
  76403. }
  76404. }, 0);
  76405. }
  76406. };
  76407. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76408. if (impostor.mass === 0) {
  76409. return null;
  76410. }
  76411. if (!this._intersectsWithCylinder(impostor)) {
  76412. return null;
  76413. }
  76414. var impostorObjectCenter = impostor.getObjectCenter();
  76415. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76416. var direction = this._originDirection;
  76417. }
  76418. else {
  76419. var direction = impostorObjectCenter.subtract(this._originTop);
  76420. }
  76421. var multiplier = this._strength * -1;
  76422. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76423. return { force: force, contactPoint: impostorObjectCenter };
  76424. };
  76425. PhysicsUpdraftEvent.prototype._tick = function () {
  76426. var _this = this;
  76427. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76428. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76429. if (!impostorForceAndContactPoint) {
  76430. return;
  76431. }
  76432. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76433. });
  76434. };
  76435. /*** Helpers ***/
  76436. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76437. if (!this._cylinder) {
  76438. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76439. height: this._height,
  76440. diameter: this._radius * 2,
  76441. }, this._scene);
  76442. this._cylinder.isVisible = false;
  76443. }
  76444. };
  76445. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76446. var impostorObject = impostor.object;
  76447. this._prepareCylinder();
  76448. this._cylinder.position = this._cylinderPosition;
  76449. return this._cylinder.intersectsMesh(impostorObject, true);
  76450. };
  76451. return PhysicsUpdraftEvent;
  76452. }());
  76453. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76454. /***** Vortex *****/
  76455. var PhysicsVortexEvent = /** @class */ (function () {
  76456. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76457. this._scene = _scene;
  76458. this._origin = _origin;
  76459. this._radius = _radius;
  76460. this._strength = _strength;
  76461. this._height = _height;
  76462. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76463. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76464. this._updraftMultiplier = 0.02;
  76465. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76466. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76467. this._physicsEngine = this._scene.getPhysicsEngine();
  76468. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76469. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76470. this._tickCallback = this._tick.bind(this);
  76471. }
  76472. /**
  76473. * Returns the data related to the vortex event (cylinder).
  76474. * @returns {PhysicsVortexEventData}
  76475. */
  76476. PhysicsVortexEvent.prototype.getData = function () {
  76477. this._dataFetched = true;
  76478. return {
  76479. cylinder: this._cylinder,
  76480. };
  76481. };
  76482. /**
  76483. * Enables the vortex.
  76484. */
  76485. PhysicsVortexEvent.prototype.enable = function () {
  76486. this._tickCallback.call(this);
  76487. this._scene.registerBeforeRender(this._tickCallback);
  76488. };
  76489. /**
  76490. * Disables the cortex.
  76491. */
  76492. PhysicsVortexEvent.prototype.disable = function () {
  76493. this._scene.unregisterBeforeRender(this._tickCallback);
  76494. };
  76495. /**
  76496. * Disposes the sphere.
  76497. * @param {bolean} force
  76498. */
  76499. PhysicsVortexEvent.prototype.dispose = function (force) {
  76500. var _this = this;
  76501. if (force === void 0) { force = true; }
  76502. if (force) {
  76503. this._cylinder.dispose();
  76504. }
  76505. else {
  76506. setTimeout(function () {
  76507. if (!_this._dataFetched) {
  76508. _this._cylinder.dispose();
  76509. }
  76510. }, 0);
  76511. }
  76512. };
  76513. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76514. if (impostor.mass === 0) {
  76515. return null;
  76516. }
  76517. if (!this._intersectsWithCylinder(impostor)) {
  76518. return null;
  76519. }
  76520. if (impostor.object.getClassName() !== 'Mesh') {
  76521. return null;
  76522. }
  76523. var impostorObject = impostor.object;
  76524. var impostorObjectCenter = impostor.getObjectCenter();
  76525. 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)
  76526. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76527. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76528. var hit = ray.intersectsMesh(impostorObject);
  76529. var contactPoint = hit.pickedPoint;
  76530. if (!contactPoint) {
  76531. return null;
  76532. }
  76533. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76534. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76535. var directionToOrigin = contactPoint.normalize();
  76536. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76537. directionToOrigin = directionToOrigin.negate();
  76538. }
  76539. // TODO: find a more physically based solution
  76540. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76541. var forceX = directionToOrigin.x * this._strength / 8;
  76542. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76543. var forceZ = directionToOrigin.z * this._strength / 8;
  76544. }
  76545. else {
  76546. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76547. var forceY = this._originTop.y * this._updraftMultiplier;
  76548. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76549. }
  76550. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76551. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76552. return { force: force, contactPoint: impostorObjectCenter };
  76553. };
  76554. PhysicsVortexEvent.prototype._tick = function () {
  76555. var _this = this;
  76556. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76557. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76558. if (!impostorForceAndContactPoint) {
  76559. return;
  76560. }
  76561. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76562. });
  76563. };
  76564. /*** Helpers ***/
  76565. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76566. if (!this._cylinder) {
  76567. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76568. height: this._height,
  76569. diameter: this._radius * 2,
  76570. }, this._scene);
  76571. this._cylinder.isVisible = false;
  76572. }
  76573. };
  76574. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76575. var impostorObject = impostor.object;
  76576. this._prepareCylinder();
  76577. this._cylinder.position = this._cylinderPosition;
  76578. return this._cylinder.intersectsMesh(impostorObject, true);
  76579. };
  76580. return PhysicsVortexEvent;
  76581. }());
  76582. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76583. /***** Enums *****/
  76584. /**
  76585. * The strenght of the force in correspondence to the distance of the affected object
  76586. */
  76587. var PhysicsRadialImpulseFalloff;
  76588. (function (PhysicsRadialImpulseFalloff) {
  76589. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76590. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76591. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76592. /**
  76593. * The strenght of the force in correspondence to the distance of the affected object
  76594. */
  76595. var PhysicsUpdraftMode;
  76596. (function (PhysicsUpdraftMode) {
  76597. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76598. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76599. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76600. })(BABYLON || (BABYLON = {}));
  76601. //# sourceMappingURL=babylon.physicsHelper.js.map
  76602. var BABYLON;
  76603. (function (BABYLON) {
  76604. var CannonJSPlugin = /** @class */ (function () {
  76605. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76606. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76607. if (iterations === void 0) { iterations = 10; }
  76608. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76609. this.name = "CannonJSPlugin";
  76610. this._physicsMaterials = new Array();
  76611. this._fixedTimeStep = 1 / 60;
  76612. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76613. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76614. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76615. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76616. this._tmpPosition = BABYLON.Vector3.Zero();
  76617. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76618. this._tmpUnityRotation = new BABYLON.Quaternion();
  76619. if (!this.isSupported()) {
  76620. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76621. return;
  76622. }
  76623. this._extendNamespace();
  76624. this.world = new this.BJSCANNON.World();
  76625. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76626. this.world.solver.iterations = iterations;
  76627. }
  76628. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76629. this.world.gravity.copy(gravity);
  76630. };
  76631. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76632. this._fixedTimeStep = timeStep;
  76633. };
  76634. CannonJSPlugin.prototype.getTimeStep = function () {
  76635. return this._fixedTimeStep;
  76636. };
  76637. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76638. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76639. };
  76640. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76641. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76642. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76643. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76644. };
  76645. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76646. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76647. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76648. impostor.physicsBody.applyForce(impulse, worldPoint);
  76649. };
  76650. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76651. //parent-child relationship. Does this impostor has a parent impostor?
  76652. if (impostor.parent) {
  76653. if (impostor.physicsBody) {
  76654. this.removePhysicsBody(impostor);
  76655. //TODO is that needed?
  76656. impostor.forceUpdate();
  76657. }
  76658. return;
  76659. }
  76660. //should a new body be created for this impostor?
  76661. if (impostor.isBodyInitRequired()) {
  76662. var shape = this._createShape(impostor);
  76663. //unregister events, if body is being changed
  76664. var oldBody = impostor.physicsBody;
  76665. if (oldBody) {
  76666. this.removePhysicsBody(impostor);
  76667. }
  76668. //create the body and material
  76669. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76670. var bodyCreationObject = {
  76671. mass: impostor.getParam("mass"),
  76672. material: material
  76673. };
  76674. // A simple extend, in case native options were used.
  76675. var nativeOptions = impostor.getParam("nativeOptions");
  76676. for (var key in nativeOptions) {
  76677. if (nativeOptions.hasOwnProperty(key)) {
  76678. bodyCreationObject[key] = nativeOptions[key];
  76679. }
  76680. }
  76681. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76682. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76683. this.world.addEventListener("preStep", impostor.beforeStep);
  76684. this.world.addEventListener("postStep", impostor.afterStep);
  76685. impostor.physicsBody.addShape(shape);
  76686. this.world.add(impostor.physicsBody);
  76687. //try to keep the body moving in the right direction by taking old properties.
  76688. //Should be tested!
  76689. if (oldBody) {
  76690. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76691. impostor.physicsBody[param].copy(oldBody[param]);
  76692. });
  76693. }
  76694. this._processChildMeshes(impostor);
  76695. }
  76696. //now update the body's transformation
  76697. this._updatePhysicsBodyTransformation(impostor);
  76698. };
  76699. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76700. var _this = this;
  76701. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76702. var currentRotation = mainImpostor.object.rotationQuaternion;
  76703. if (meshChildren.length) {
  76704. var processMesh = function (localPosition, mesh) {
  76705. if (!currentRotation || !mesh.rotationQuaternion) {
  76706. return;
  76707. }
  76708. var childImpostor = mesh.getPhysicsImpostor();
  76709. if (childImpostor) {
  76710. var parent = childImpostor.parent;
  76711. if (parent !== mainImpostor) {
  76712. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76713. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76714. if (childImpostor.physicsBody) {
  76715. _this.removePhysicsBody(childImpostor);
  76716. childImpostor.physicsBody = null;
  76717. }
  76718. childImpostor.parent = mainImpostor;
  76719. childImpostor.resetUpdateFlags();
  76720. 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));
  76721. //Add the mass of the children.
  76722. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76723. }
  76724. }
  76725. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76726. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76727. };
  76728. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76729. }
  76730. };
  76731. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76732. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76733. this.world.removeEventListener("preStep", impostor.beforeStep);
  76734. this.world.removeEventListener("postStep", impostor.afterStep);
  76735. this.world.remove(impostor.physicsBody);
  76736. };
  76737. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76738. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76739. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76740. if (!mainBody || !connectedBody) {
  76741. return;
  76742. }
  76743. var constraint;
  76744. var jointData = impostorJoint.joint.jointData;
  76745. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76746. var constraintData = {
  76747. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76748. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76749. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76750. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76751. maxForce: jointData.nativeParams.maxForce,
  76752. collideConnected: !!jointData.collision
  76753. };
  76754. switch (impostorJoint.joint.type) {
  76755. case BABYLON.PhysicsJoint.HingeJoint:
  76756. case BABYLON.PhysicsJoint.Hinge2Joint:
  76757. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76758. break;
  76759. case BABYLON.PhysicsJoint.DistanceJoint:
  76760. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76761. break;
  76762. case BABYLON.PhysicsJoint.SpringJoint:
  76763. var springData = jointData;
  76764. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76765. restLength: springData.length,
  76766. stiffness: springData.stiffness,
  76767. damping: springData.damping,
  76768. localAnchorA: constraintData.pivotA,
  76769. localAnchorB: constraintData.pivotB
  76770. });
  76771. break;
  76772. case BABYLON.PhysicsJoint.LockJoint:
  76773. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76774. break;
  76775. case BABYLON.PhysicsJoint.PointToPointJoint:
  76776. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76777. default:
  76778. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76779. break;
  76780. }
  76781. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76782. constraint.collideConnected = !!jointData.collision;
  76783. impostorJoint.joint.physicsJoint = constraint;
  76784. //don't add spring as constraint, as it is not one.
  76785. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76786. this.world.addConstraint(constraint);
  76787. }
  76788. else {
  76789. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76790. constraint.applyForce();
  76791. });
  76792. }
  76793. };
  76794. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76795. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76796. };
  76797. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76798. var index;
  76799. var mat;
  76800. for (index = 0; index < this._physicsMaterials.length; index++) {
  76801. mat = this._physicsMaterials[index];
  76802. if (mat.friction === friction && mat.restitution === restitution) {
  76803. return mat;
  76804. }
  76805. }
  76806. var currentMat = new this.BJSCANNON.Material(name);
  76807. currentMat.friction = friction;
  76808. currentMat.restitution = restitution;
  76809. this._physicsMaterials.push(currentMat);
  76810. return currentMat;
  76811. };
  76812. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76813. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76814. };
  76815. CannonJSPlugin.prototype._createShape = function (impostor) {
  76816. var object = impostor.object;
  76817. var returnValue;
  76818. var extendSize = impostor.getObjectExtendSize();
  76819. switch (impostor.type) {
  76820. case BABYLON.PhysicsImpostor.SphereImpostor:
  76821. var radiusX = extendSize.x;
  76822. var radiusY = extendSize.y;
  76823. var radiusZ = extendSize.z;
  76824. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76825. break;
  76826. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76827. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76828. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76829. break;
  76830. case BABYLON.PhysicsImpostor.BoxImpostor:
  76831. var box = extendSize.scale(0.5);
  76832. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76833. break;
  76834. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76835. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76836. returnValue = new this.BJSCANNON.Plane();
  76837. break;
  76838. case BABYLON.PhysicsImpostor.MeshImpostor:
  76839. // should transform the vertex data to world coordinates!!
  76840. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76841. var rawFaces = object.getIndices ? object.getIndices() : [];
  76842. if (!rawVerts)
  76843. return;
  76844. // get only scale! so the object could transform correctly.
  76845. var oldPosition = object.position.clone();
  76846. var oldRotation = object.rotation && object.rotation.clone();
  76847. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76848. object.position.copyFromFloats(0, 0, 0);
  76849. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76850. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76851. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76852. var transform = object.computeWorldMatrix(true);
  76853. // convert rawVerts to object space
  76854. var temp = new Array();
  76855. var index;
  76856. for (index = 0; index < rawVerts.length; index += 3) {
  76857. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76858. }
  76859. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76860. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76861. //now set back the transformation!
  76862. object.position.copyFrom(oldPosition);
  76863. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76864. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76865. break;
  76866. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76867. var oldPosition2 = object.position.clone();
  76868. var oldRotation2 = object.rotation && object.rotation.clone();
  76869. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76870. object.position.copyFromFloats(0, 0, 0);
  76871. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76872. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76873. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76874. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76875. returnValue = this._createHeightmap(object);
  76876. object.position.copyFrom(oldPosition2);
  76877. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76878. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76879. object.computeWorldMatrix(true);
  76880. break;
  76881. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76882. returnValue = new this.BJSCANNON.Particle();
  76883. break;
  76884. }
  76885. return returnValue;
  76886. };
  76887. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76888. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76889. var transform = object.computeWorldMatrix(true);
  76890. // convert rawVerts to object space
  76891. var temp = new Array();
  76892. var index;
  76893. for (index = 0; index < pos.length; index += 3) {
  76894. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76895. }
  76896. pos = temp;
  76897. var matrix = new Array();
  76898. //For now pointDepth will not be used and will be automatically calculated.
  76899. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76900. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76901. var boundingInfo = object.getBoundingInfo();
  76902. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76903. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76904. var elementSize = dim * 2 / arraySize;
  76905. for (var i = 0; i < pos.length; i = i + 3) {
  76906. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76907. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76908. var y = -pos[i + 2] + minY;
  76909. if (!matrix[x]) {
  76910. matrix[x] = [];
  76911. }
  76912. if (!matrix[x][z]) {
  76913. matrix[x][z] = y;
  76914. }
  76915. matrix[x][z] = Math.max(y, matrix[x][z]);
  76916. }
  76917. for (var x = 0; x <= arraySize; ++x) {
  76918. if (!matrix[x]) {
  76919. var loc = 1;
  76920. while (!matrix[(x + loc) % arraySize]) {
  76921. loc++;
  76922. }
  76923. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76924. //console.log("missing x", x);
  76925. }
  76926. for (var z = 0; z <= arraySize; ++z) {
  76927. if (!matrix[x][z]) {
  76928. var loc = 1;
  76929. var newValue;
  76930. while (newValue === undefined) {
  76931. newValue = matrix[x][(z + loc++) % arraySize];
  76932. }
  76933. matrix[x][z] = newValue;
  76934. }
  76935. }
  76936. }
  76937. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76938. elementSize: elementSize
  76939. });
  76940. //For future reference, needed for body transformation
  76941. shape.minY = minY;
  76942. return shape;
  76943. };
  76944. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76945. var object = impostor.object;
  76946. //make sure it is updated...
  76947. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76948. // The delta between the mesh position and the mesh bounding box center
  76949. var bInfo = object.getBoundingInfo();
  76950. if (!bInfo)
  76951. return;
  76952. var center = impostor.getObjectCenter();
  76953. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76954. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76955. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76956. this._tmpPosition.copyFrom(center);
  76957. var quaternion = object.rotationQuaternion;
  76958. if (!quaternion) {
  76959. return;
  76960. }
  76961. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76962. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76963. //-90 DEG in X, precalculated
  76964. quaternion = quaternion.multiply(this._minus90X);
  76965. //Invert! (Precalculated, 90 deg in X)
  76966. //No need to clone. this will never change.
  76967. impostor.setDeltaRotation(this._plus90X);
  76968. }
  76969. //If it is a heightfield, if should be centered.
  76970. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76971. var mesh = object;
  76972. var boundingInfo = mesh.getBoundingInfo();
  76973. //calculate the correct body position:
  76974. var rotationQuaternion = mesh.rotationQuaternion;
  76975. mesh.rotationQuaternion = this._tmpUnityRotation;
  76976. mesh.computeWorldMatrix(true);
  76977. //get original center with no rotation
  76978. var c = center.clone();
  76979. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76980. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76981. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76982. mesh.setPreTransformMatrix(p);
  76983. mesh.computeWorldMatrix(true);
  76984. //calculate the translation
  76985. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76986. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76987. //add it inverted to the delta
  76988. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76989. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76990. //rotation is back
  76991. mesh.rotationQuaternion = rotationQuaternion;
  76992. mesh.setPreTransformMatrix(oldPivot);
  76993. mesh.computeWorldMatrix(true);
  76994. }
  76995. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76996. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76997. //this._tmpPosition.copyFrom(object.position);
  76998. }
  76999. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77000. //Now update the impostor object
  77001. impostor.physicsBody.position.copy(this._tmpPosition);
  77002. impostor.physicsBody.quaternion.copy(quaternion);
  77003. };
  77004. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77005. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77006. if (impostor.object.rotationQuaternion) {
  77007. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77008. }
  77009. };
  77010. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77011. impostor.physicsBody.position.copy(newPosition);
  77012. impostor.physicsBody.quaternion.copy(newRotation);
  77013. };
  77014. CannonJSPlugin.prototype.isSupported = function () {
  77015. return this.BJSCANNON !== undefined;
  77016. };
  77017. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77018. impostor.physicsBody.velocity.copy(velocity);
  77019. };
  77020. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77021. impostor.physicsBody.angularVelocity.copy(velocity);
  77022. };
  77023. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77024. var v = impostor.physicsBody.velocity;
  77025. if (!v) {
  77026. return null;
  77027. }
  77028. return new BABYLON.Vector3(v.x, v.y, v.z);
  77029. };
  77030. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77031. var v = impostor.physicsBody.angularVelocity;
  77032. if (!v) {
  77033. return null;
  77034. }
  77035. return new BABYLON.Vector3(v.x, v.y, v.z);
  77036. };
  77037. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77038. impostor.physicsBody.mass = mass;
  77039. impostor.physicsBody.updateMassProperties();
  77040. };
  77041. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77042. return impostor.physicsBody.mass;
  77043. };
  77044. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77045. return impostor.physicsBody.material.friction;
  77046. };
  77047. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77048. impostor.physicsBody.material.friction = friction;
  77049. };
  77050. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77051. return impostor.physicsBody.material.restitution;
  77052. };
  77053. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77054. impostor.physicsBody.material.restitution = restitution;
  77055. };
  77056. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77057. impostor.physicsBody.sleep();
  77058. };
  77059. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77060. impostor.physicsBody.wakeUp();
  77061. };
  77062. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77063. joint.physicsJoint.distance = maxDistance;
  77064. };
  77065. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77066. // if (!motorIndex) {
  77067. // joint.physicsJoint.enableMotor();
  77068. // }
  77069. // }
  77070. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77071. // if (!motorIndex) {
  77072. // joint.physicsJoint.disableMotor();
  77073. // }
  77074. // }
  77075. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77076. if (!motorIndex) {
  77077. joint.physicsJoint.enableMotor();
  77078. joint.physicsJoint.setMotorSpeed(speed);
  77079. if (maxForce) {
  77080. this.setLimit(joint, maxForce);
  77081. }
  77082. }
  77083. };
  77084. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77085. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77086. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77087. };
  77088. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77089. var body = impostor.physicsBody;
  77090. mesh.position.x = body.position.x;
  77091. mesh.position.y = body.position.y;
  77092. mesh.position.z = body.position.z;
  77093. if (mesh.rotationQuaternion) {
  77094. mesh.rotationQuaternion.x = body.quaternion.x;
  77095. mesh.rotationQuaternion.y = body.quaternion.y;
  77096. mesh.rotationQuaternion.z = body.quaternion.z;
  77097. mesh.rotationQuaternion.w = body.quaternion.w;
  77098. }
  77099. };
  77100. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77101. var shape = impostor.physicsBody.shapes[0];
  77102. return shape.boundingSphereRadius;
  77103. };
  77104. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77105. var shape = impostor.physicsBody.shapes[0];
  77106. result.x = shape.halfExtents.x * 2;
  77107. result.y = shape.halfExtents.y * 2;
  77108. result.z = shape.halfExtents.z * 2;
  77109. };
  77110. CannonJSPlugin.prototype.dispose = function () {
  77111. };
  77112. CannonJSPlugin.prototype._extendNamespace = function () {
  77113. //this will force cannon to execute at least one step when using interpolation
  77114. var step_tmp1 = new this.BJSCANNON.Vec3();
  77115. var Engine = this.BJSCANNON;
  77116. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77117. maxSubSteps = maxSubSteps || 10;
  77118. timeSinceLastCalled = timeSinceLastCalled || 0;
  77119. if (timeSinceLastCalled === 0) {
  77120. this.internalStep(dt);
  77121. this.time += dt;
  77122. }
  77123. else {
  77124. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77125. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77126. var t0 = performance.now();
  77127. for (var i = 0; i !== internalSteps; i++) {
  77128. this.internalStep(dt);
  77129. if (performance.now() - t0 > dt * 1000) {
  77130. break;
  77131. }
  77132. }
  77133. this.time += timeSinceLastCalled;
  77134. var h = this.time % dt;
  77135. var h_div_dt = h / dt;
  77136. var interpvelo = step_tmp1;
  77137. var bodies = this.bodies;
  77138. for (var j = 0; j !== bodies.length; j++) {
  77139. var b = bodies[j];
  77140. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77141. b.position.vsub(b.previousPosition, interpvelo);
  77142. interpvelo.scale(h_div_dt, interpvelo);
  77143. b.position.vadd(interpvelo, b.interpolatedPosition);
  77144. }
  77145. else {
  77146. b.interpolatedPosition.copy(b.position);
  77147. b.interpolatedQuaternion.copy(b.quaternion);
  77148. }
  77149. }
  77150. }
  77151. };
  77152. };
  77153. return CannonJSPlugin;
  77154. }());
  77155. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77156. })(BABYLON || (BABYLON = {}));
  77157. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77158. var BABYLON;
  77159. (function (BABYLON) {
  77160. var OimoJSPlugin = /** @class */ (function () {
  77161. function OimoJSPlugin(iterations) {
  77162. this.name = "OimoJSPlugin";
  77163. this._tmpImpostorsArray = [];
  77164. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77165. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  77166. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77167. this.world.worldscale(1);
  77168. this.world.clear();
  77169. //making sure no stats are calculated
  77170. this.world.isNoStat = true;
  77171. }
  77172. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77173. this.world.gravity.copy(gravity);
  77174. };
  77175. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77176. this.world.timeStep = timeStep;
  77177. };
  77178. OimoJSPlugin.prototype.getTimeStep = function () {
  77179. return this.world.timeStep;
  77180. };
  77181. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77182. var _this = this;
  77183. impostors.forEach(function (impostor) {
  77184. impostor.beforeStep();
  77185. });
  77186. this.world.step();
  77187. impostors.forEach(function (impostor) {
  77188. impostor.afterStep();
  77189. //update the ordered impostors array
  77190. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77191. });
  77192. //check for collisions
  77193. var contact = this.world.contacts;
  77194. while (contact !== null) {
  77195. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77196. contact = contact.next;
  77197. continue;
  77198. }
  77199. //is this body colliding with any other? get the impostor
  77200. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77201. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77202. if (!mainImpostor || !collidingImpostor) {
  77203. contact = contact.next;
  77204. continue;
  77205. }
  77206. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77207. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77208. contact = contact.next;
  77209. }
  77210. };
  77211. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77212. var mass = impostor.physicsBody.massInfo.mass;
  77213. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77214. };
  77215. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77216. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77217. this.applyImpulse(impostor, force, contactPoint);
  77218. };
  77219. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77220. var _this = this;
  77221. //parent-child relationship. Does this impostor has a parent impostor?
  77222. if (impostor.parent) {
  77223. if (impostor.physicsBody) {
  77224. this.removePhysicsBody(impostor);
  77225. //TODO is that needed?
  77226. impostor.forceUpdate();
  77227. }
  77228. return;
  77229. }
  77230. if (impostor.isBodyInitRequired()) {
  77231. var bodyConfig = {
  77232. name: impostor.uniqueId,
  77233. //Oimo must have mass, also for static objects.
  77234. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77235. size: [],
  77236. type: [],
  77237. pos: [],
  77238. rot: [],
  77239. move: impostor.getParam("mass") !== 0,
  77240. //Supporting older versions of Oimo
  77241. world: this.world
  77242. };
  77243. var impostors = [impostor];
  77244. var addToArray = function (parent) {
  77245. if (!parent.getChildMeshes)
  77246. return;
  77247. parent.getChildMeshes().forEach(function (m) {
  77248. if (m.physicsImpostor) {
  77249. impostors.push(m.physicsImpostor);
  77250. //m.physicsImpostor._init();
  77251. }
  77252. });
  77253. };
  77254. addToArray(impostor.object);
  77255. var checkWithEpsilon_1 = function (value) {
  77256. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77257. };
  77258. impostors.forEach(function (i) {
  77259. if (!impostor.object.rotationQuaternion) {
  77260. return;
  77261. }
  77262. //get the correct bounding box
  77263. var oldQuaternion = i.object.rotationQuaternion;
  77264. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77265. x: impostor.object.rotationQuaternion.x,
  77266. y: impostor.object.rotationQuaternion.y,
  77267. z: impostor.object.rotationQuaternion.z,
  77268. s: impostor.object.rotationQuaternion.w
  77269. });
  77270. var extendSize = i.getObjectExtendSize();
  77271. if (i === impostor) {
  77272. var center = impostor.getObjectCenter();
  77273. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77274. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77275. //Can also use Array.prototype.push.apply
  77276. bodyConfig.pos.push(center.x);
  77277. bodyConfig.pos.push(center.y);
  77278. bodyConfig.pos.push(center.z);
  77279. //tmp solution
  77280. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77281. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77282. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77283. }
  77284. else {
  77285. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77286. bodyConfig.pos.push(localPosition.x);
  77287. bodyConfig.pos.push(localPosition.y);
  77288. bodyConfig.pos.push(localPosition.z);
  77289. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77290. bodyConfig.rot.push(0);
  77291. bodyConfig.rot.push(0);
  77292. bodyConfig.rot.push(0);
  77293. }
  77294. // register mesh
  77295. switch (i.type) {
  77296. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77297. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77298. case BABYLON.PhysicsImpostor.SphereImpostor:
  77299. var radiusX = extendSize.x;
  77300. var radiusY = extendSize.y;
  77301. var radiusZ = extendSize.z;
  77302. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77303. bodyConfig.type.push('sphere');
  77304. //due to the way oimo works with compounds, add 3 times
  77305. bodyConfig.size.push(size);
  77306. bodyConfig.size.push(size);
  77307. bodyConfig.size.push(size);
  77308. break;
  77309. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77310. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77311. var sizeY = checkWithEpsilon_1(extendSize.y);
  77312. bodyConfig.type.push('cylinder');
  77313. bodyConfig.size.push(sizeX);
  77314. bodyConfig.size.push(sizeY);
  77315. //due to the way oimo works with compounds, add one more value.
  77316. bodyConfig.size.push(sizeY);
  77317. break;
  77318. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77319. case BABYLON.PhysicsImpostor.BoxImpostor:
  77320. default:
  77321. var sizeX = checkWithEpsilon_1(extendSize.x);
  77322. var sizeY = checkWithEpsilon_1(extendSize.y);
  77323. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77324. bodyConfig.type.push('box');
  77325. bodyConfig.size.push(sizeX);
  77326. bodyConfig.size.push(sizeY);
  77327. bodyConfig.size.push(sizeZ);
  77328. break;
  77329. }
  77330. //actually not needed, but hey...
  77331. i.object.rotationQuaternion = oldQuaternion;
  77332. });
  77333. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77334. }
  77335. else {
  77336. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77337. }
  77338. impostor.setDeltaPosition(this._tmpPositionVector);
  77339. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77340. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77341. };
  77342. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77343. //impostor.physicsBody.dispose();
  77344. //Same as : (older oimo versions)
  77345. this.world.removeRigidBody(impostor.physicsBody);
  77346. };
  77347. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77348. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77349. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77350. if (!mainBody || !connectedBody) {
  77351. return;
  77352. }
  77353. var jointData = impostorJoint.joint.jointData;
  77354. var options = jointData.nativeParams || {};
  77355. var type;
  77356. var nativeJointData = {
  77357. body1: mainBody,
  77358. body2: connectedBody,
  77359. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77360. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77361. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77362. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77363. min: options.min,
  77364. max: options.max,
  77365. collision: options.collision || jointData.collision,
  77366. spring: options.spring,
  77367. //supporting older version of Oimo
  77368. world: this.world
  77369. };
  77370. switch (impostorJoint.joint.type) {
  77371. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77372. type = "jointBall";
  77373. break;
  77374. case BABYLON.PhysicsJoint.SpringJoint:
  77375. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77376. var springData = jointData;
  77377. nativeJointData.min = springData.length || nativeJointData.min;
  77378. //Max should also be set, just make sure it is at least min
  77379. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77380. case BABYLON.PhysicsJoint.DistanceJoint:
  77381. type = "jointDistance";
  77382. nativeJointData.max = jointData.maxDistance;
  77383. break;
  77384. case BABYLON.PhysicsJoint.PrismaticJoint:
  77385. type = "jointPrisme";
  77386. break;
  77387. case BABYLON.PhysicsJoint.SliderJoint:
  77388. type = "jointSlide";
  77389. break;
  77390. case BABYLON.PhysicsJoint.WheelJoint:
  77391. type = "jointWheel";
  77392. break;
  77393. case BABYLON.PhysicsJoint.HingeJoint:
  77394. default:
  77395. type = "jointHinge";
  77396. break;
  77397. }
  77398. nativeJointData.type = type;
  77399. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77400. };
  77401. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77402. //Bug in Oimo prevents us from disposing a joint in the playground
  77403. //joint.joint.physicsJoint.dispose();
  77404. //So we will bruteforce it!
  77405. try {
  77406. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77407. }
  77408. catch (e) {
  77409. BABYLON.Tools.Warn(e);
  77410. }
  77411. };
  77412. OimoJSPlugin.prototype.isSupported = function () {
  77413. return this.BJSOIMO !== undefined;
  77414. };
  77415. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77416. if (!impostor.physicsBody.sleeping) {
  77417. //TODO check that
  77418. if (impostor.physicsBody.shapes.next) {
  77419. var parentShape = this._getLastShape(impostor.physicsBody);
  77420. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77421. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77422. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77423. }
  77424. else {
  77425. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77426. }
  77427. if (impostor.object.rotationQuaternion) {
  77428. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77429. impostor.object.rotationQuaternion.normalize();
  77430. }
  77431. }
  77432. };
  77433. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77434. var body = impostor.physicsBody;
  77435. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77436. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77437. body.syncShapes();
  77438. body.awake();
  77439. };
  77440. OimoJSPlugin.prototype._getLastShape = function (body) {
  77441. var lastShape = body.shapes;
  77442. while (lastShape.next) {
  77443. lastShape = lastShape.next;
  77444. }
  77445. return lastShape;
  77446. };
  77447. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77448. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77449. };
  77450. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77451. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77452. };
  77453. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77454. var v = impostor.physicsBody.linearVelocity;
  77455. if (!v) {
  77456. return null;
  77457. }
  77458. return new BABYLON.Vector3(v.x, v.y, v.z);
  77459. };
  77460. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77461. var v = impostor.physicsBody.angularVelocity;
  77462. if (!v) {
  77463. return null;
  77464. }
  77465. return new BABYLON.Vector3(v.x, v.y, v.z);
  77466. };
  77467. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77468. var staticBody = mass === 0;
  77469. //this will actually set the body's density and not its mass.
  77470. //But this is how oimo treats the mass variable.
  77471. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77472. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77473. };
  77474. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77475. return impostor.physicsBody.shapes.density;
  77476. };
  77477. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77478. return impostor.physicsBody.shapes.friction;
  77479. };
  77480. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77481. impostor.physicsBody.shapes.friction = friction;
  77482. };
  77483. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77484. return impostor.physicsBody.shapes.restitution;
  77485. };
  77486. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77487. impostor.physicsBody.shapes.restitution = restitution;
  77488. };
  77489. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77490. impostor.physicsBody.sleep();
  77491. };
  77492. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77493. impostor.physicsBody.awake();
  77494. };
  77495. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77496. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77497. if (minDistance !== void 0) {
  77498. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77499. }
  77500. };
  77501. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77502. //TODO separate rotational and transational motors.
  77503. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77504. if (motor) {
  77505. motor.setMotor(speed, maxForce);
  77506. }
  77507. };
  77508. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77509. //TODO separate rotational and transational motors.
  77510. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77511. if (motor) {
  77512. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77513. }
  77514. };
  77515. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77516. var body = impostor.physicsBody;
  77517. mesh.position.x = body.position.x;
  77518. mesh.position.y = body.position.y;
  77519. mesh.position.z = body.position.z;
  77520. if (mesh.rotationQuaternion) {
  77521. mesh.rotationQuaternion.x = body.orientation.x;
  77522. mesh.rotationQuaternion.y = body.orientation.y;
  77523. mesh.rotationQuaternion.z = body.orientation.z;
  77524. mesh.rotationQuaternion.w = body.orientation.s;
  77525. }
  77526. };
  77527. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77528. return impostor.physicsBody.shapes.radius;
  77529. };
  77530. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77531. var shape = impostor.physicsBody.shapes;
  77532. result.x = shape.halfWidth * 2;
  77533. result.y = shape.halfHeight * 2;
  77534. result.z = shape.halfDepth * 2;
  77535. };
  77536. OimoJSPlugin.prototype.dispose = function () {
  77537. this.world.clear();
  77538. };
  77539. return OimoJSPlugin;
  77540. }());
  77541. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77542. })(BABYLON || (BABYLON = {}));
  77543. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77544. var BABYLON;
  77545. (function (BABYLON) {
  77546. /*
  77547. * Based on jsTGALoader - Javascript loader for TGA file
  77548. * By Vincent Thibault
  77549. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77550. */
  77551. var TGATools = /** @class */ (function () {
  77552. function TGATools() {
  77553. }
  77554. TGATools.GetTGAHeader = function (data) {
  77555. var offset = 0;
  77556. var header = {
  77557. id_length: data[offset++],
  77558. colormap_type: data[offset++],
  77559. image_type: data[offset++],
  77560. colormap_index: data[offset++] | data[offset++] << 8,
  77561. colormap_length: data[offset++] | data[offset++] << 8,
  77562. colormap_size: data[offset++],
  77563. origin: [
  77564. data[offset++] | data[offset++] << 8,
  77565. data[offset++] | data[offset++] << 8
  77566. ],
  77567. width: data[offset++] | data[offset++] << 8,
  77568. height: data[offset++] | data[offset++] << 8,
  77569. pixel_size: data[offset++],
  77570. flags: data[offset++]
  77571. };
  77572. return header;
  77573. };
  77574. TGATools.UploadContent = function (gl, data) {
  77575. // Not enough data to contain header ?
  77576. if (data.length < 19) {
  77577. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77578. return;
  77579. }
  77580. // Read Header
  77581. var offset = 18;
  77582. var header = TGATools.GetTGAHeader(data);
  77583. // Assume it's a valid Targa file.
  77584. if (header.id_length + offset > data.length) {
  77585. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77586. return;
  77587. }
  77588. // Skip not needed data
  77589. offset += header.id_length;
  77590. var use_rle = false;
  77591. var use_pal = false;
  77592. var use_grey = false;
  77593. // Get some informations.
  77594. switch (header.image_type) {
  77595. case TGATools._TYPE_RLE_INDEXED:
  77596. use_rle = true;
  77597. case TGATools._TYPE_INDEXED:
  77598. use_pal = true;
  77599. break;
  77600. case TGATools._TYPE_RLE_RGB:
  77601. use_rle = true;
  77602. case TGATools._TYPE_RGB:
  77603. // use_rgb = true;
  77604. break;
  77605. case TGATools._TYPE_RLE_GREY:
  77606. use_rle = true;
  77607. case TGATools._TYPE_GREY:
  77608. use_grey = true;
  77609. break;
  77610. }
  77611. var pixel_data;
  77612. // var numAlphaBits = header.flags & 0xf;
  77613. var pixel_size = header.pixel_size >> 3;
  77614. var pixel_total = header.width * header.height * pixel_size;
  77615. // Read palettes
  77616. var palettes;
  77617. if (use_pal) {
  77618. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77619. }
  77620. // Read LRE
  77621. if (use_rle) {
  77622. pixel_data = new Uint8Array(pixel_total);
  77623. var c, count, i;
  77624. var localOffset = 0;
  77625. var pixels = new Uint8Array(pixel_size);
  77626. while (offset < pixel_total && localOffset < pixel_total) {
  77627. c = data[offset++];
  77628. count = (c & 0x7f) + 1;
  77629. // RLE pixels
  77630. if (c & 0x80) {
  77631. // Bind pixel tmp array
  77632. for (i = 0; i < pixel_size; ++i) {
  77633. pixels[i] = data[offset++];
  77634. }
  77635. // Copy pixel array
  77636. for (i = 0; i < count; ++i) {
  77637. pixel_data.set(pixels, localOffset + i * pixel_size);
  77638. }
  77639. localOffset += pixel_size * count;
  77640. }
  77641. else {
  77642. count *= pixel_size;
  77643. for (i = 0; i < count; ++i) {
  77644. pixel_data[localOffset + i] = data[offset++];
  77645. }
  77646. localOffset += count;
  77647. }
  77648. }
  77649. }
  77650. else {
  77651. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77652. }
  77653. // Load to texture
  77654. var x_start, y_start, x_step, y_step, y_end, x_end;
  77655. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77656. default:
  77657. case TGATools._ORIGIN_UL:
  77658. x_start = 0;
  77659. x_step = 1;
  77660. x_end = header.width;
  77661. y_start = 0;
  77662. y_step = 1;
  77663. y_end = header.height;
  77664. break;
  77665. case TGATools._ORIGIN_BL:
  77666. x_start = 0;
  77667. x_step = 1;
  77668. x_end = header.width;
  77669. y_start = header.height - 1;
  77670. y_step = -1;
  77671. y_end = -1;
  77672. break;
  77673. case TGATools._ORIGIN_UR:
  77674. x_start = header.width - 1;
  77675. x_step = -1;
  77676. x_end = -1;
  77677. y_start = 0;
  77678. y_step = 1;
  77679. y_end = header.height;
  77680. break;
  77681. case TGATools._ORIGIN_BR:
  77682. x_start = header.width - 1;
  77683. x_step = -1;
  77684. x_end = -1;
  77685. y_start = header.height - 1;
  77686. y_step = -1;
  77687. y_end = -1;
  77688. break;
  77689. }
  77690. // Load the specify method
  77691. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77692. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77693. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77694. };
  77695. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77696. var image = pixel_data, colormap = palettes;
  77697. var width = header.width, height = header.height;
  77698. var color, i = 0, x, y;
  77699. var imageData = new Uint8Array(width * height * 4);
  77700. for (y = y_start; y !== y_end; y += y_step) {
  77701. for (x = x_start; x !== x_end; x += x_step, i++) {
  77702. color = image[i];
  77703. imageData[(x + width * y) * 4 + 3] = 255;
  77704. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77705. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77706. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77707. }
  77708. }
  77709. return imageData;
  77710. };
  77711. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77712. var image = pixel_data;
  77713. var width = header.width, height = header.height;
  77714. var color, i = 0, x, y;
  77715. var imageData = new Uint8Array(width * height * 4);
  77716. for (y = y_start; y !== y_end; y += y_step) {
  77717. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77718. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77719. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  77720. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  77721. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  77722. imageData[(x + width * y) * 4 + 0] = r;
  77723. imageData[(x + width * y) * 4 + 1] = g;
  77724. imageData[(x + width * y) * 4 + 2] = b;
  77725. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77726. }
  77727. }
  77728. return imageData;
  77729. };
  77730. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77731. var image = pixel_data;
  77732. var width = header.width, height = header.height;
  77733. var i = 0, x, y;
  77734. var imageData = new Uint8Array(width * height * 4);
  77735. for (y = y_start; y !== y_end; y += y_step) {
  77736. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77737. imageData[(x + width * y) * 4 + 3] = 255;
  77738. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77739. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77740. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77741. }
  77742. }
  77743. return imageData;
  77744. };
  77745. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77746. var image = pixel_data;
  77747. var width = header.width, height = header.height;
  77748. var i = 0, x, y;
  77749. var imageData = new Uint8Array(width * height * 4);
  77750. for (y = y_start; y !== y_end; y += y_step) {
  77751. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77752. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77753. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77754. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77755. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77756. }
  77757. }
  77758. return imageData;
  77759. };
  77760. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77761. var image = pixel_data;
  77762. var width = header.width, height = header.height;
  77763. var color, i = 0, x, y;
  77764. var imageData = new Uint8Array(width * height * 4);
  77765. for (y = y_start; y !== y_end; y += y_step) {
  77766. for (x = x_start; x !== x_end; x += x_step, i++) {
  77767. color = image[i];
  77768. imageData[(x + width * y) * 4 + 0] = color;
  77769. imageData[(x + width * y) * 4 + 1] = color;
  77770. imageData[(x + width * y) * 4 + 2] = color;
  77771. imageData[(x + width * y) * 4 + 3] = 255;
  77772. }
  77773. }
  77774. return imageData;
  77775. };
  77776. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77777. var image = pixel_data;
  77778. var width = header.width, height = header.height;
  77779. var i = 0, x, y;
  77780. var imageData = new Uint8Array(width * height * 4);
  77781. for (y = y_start; y !== y_end; y += y_step) {
  77782. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77783. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77784. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77785. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77786. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77787. }
  77788. }
  77789. return imageData;
  77790. };
  77791. //private static _TYPE_NO_DATA = 0;
  77792. TGATools._TYPE_INDEXED = 1;
  77793. TGATools._TYPE_RGB = 2;
  77794. TGATools._TYPE_GREY = 3;
  77795. TGATools._TYPE_RLE_INDEXED = 9;
  77796. TGATools._TYPE_RLE_RGB = 10;
  77797. TGATools._TYPE_RLE_GREY = 11;
  77798. TGATools._ORIGIN_MASK = 0x30;
  77799. TGATools._ORIGIN_SHIFT = 0x04;
  77800. TGATools._ORIGIN_BL = 0x00;
  77801. TGATools._ORIGIN_BR = 0x01;
  77802. TGATools._ORIGIN_UL = 0x02;
  77803. TGATools._ORIGIN_UR = 0x03;
  77804. return TGATools;
  77805. }());
  77806. BABYLON.TGATools = TGATools;
  77807. })(BABYLON || (BABYLON = {}));
  77808. //# sourceMappingURL=babylon.tga.js.map
  77809. var BABYLON;
  77810. (function (BABYLON) {
  77811. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77812. // All values and structures referenced from:
  77813. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77814. var DDS_MAGIC = 0x20534444;
  77815. var
  77816. //DDSD_CAPS = 0x1,
  77817. //DDSD_HEIGHT = 0x2,
  77818. //DDSD_WIDTH = 0x4,
  77819. //DDSD_PITCH = 0x8,
  77820. //DDSD_PIXELFORMAT = 0x1000,
  77821. DDSD_MIPMAPCOUNT = 0x20000;
  77822. //DDSD_LINEARSIZE = 0x80000,
  77823. //DDSD_DEPTH = 0x800000;
  77824. // var DDSCAPS_COMPLEX = 0x8,
  77825. // DDSCAPS_MIPMAP = 0x400000,
  77826. // DDSCAPS_TEXTURE = 0x1000;
  77827. var DDSCAPS2_CUBEMAP = 0x200;
  77828. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77829. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77830. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77831. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77832. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77833. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77834. // DDSCAPS2_VOLUME = 0x200000;
  77835. var
  77836. //DDPF_ALPHAPIXELS = 0x1,
  77837. //DDPF_ALPHA = 0x2,
  77838. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77839. //DDPF_YUV = 0x200,
  77840. DDPF_LUMINANCE = 0x20000;
  77841. function FourCCToInt32(value) {
  77842. return value.charCodeAt(0) +
  77843. (value.charCodeAt(1) << 8) +
  77844. (value.charCodeAt(2) << 16) +
  77845. (value.charCodeAt(3) << 24);
  77846. }
  77847. function Int32ToFourCC(value) {
  77848. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77849. }
  77850. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77851. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77852. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77853. var FOURCC_DX10 = FourCCToInt32("DX10");
  77854. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77855. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77856. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77857. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77858. var headerLengthInt = 31; // The header length in 32 bit ints
  77859. // Offsets into the header array
  77860. var off_magic = 0;
  77861. var off_size = 1;
  77862. var off_flags = 2;
  77863. var off_height = 3;
  77864. var off_width = 4;
  77865. var off_mipmapCount = 7;
  77866. var off_pfFlags = 20;
  77867. var off_pfFourCC = 21;
  77868. var off_RGBbpp = 22;
  77869. var off_RMask = 23;
  77870. var off_GMask = 24;
  77871. var off_BMask = 25;
  77872. var off_AMask = 26;
  77873. // var off_caps1 = 27;
  77874. var off_caps2 = 28;
  77875. // var off_caps3 = 29;
  77876. // var off_caps4 = 30;
  77877. var off_dxgiFormat = 32;
  77878. ;
  77879. var DDSTools = /** @class */ (function () {
  77880. function DDSTools() {
  77881. }
  77882. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77883. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77884. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77885. var mipmapCount = 1;
  77886. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77887. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77888. }
  77889. var fourCC = header[off_pfFourCC];
  77890. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77891. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77892. switch (fourCC) {
  77893. case FOURCC_D3DFMT_R16G16B16A16F:
  77894. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77895. break;
  77896. case FOURCC_D3DFMT_R32G32B32A32F:
  77897. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77898. break;
  77899. case FOURCC_DX10:
  77900. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77901. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77902. break;
  77903. }
  77904. }
  77905. return {
  77906. width: header[off_width],
  77907. height: header[off_height],
  77908. mipmapCount: mipmapCount,
  77909. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77910. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77911. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77912. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77913. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77914. dxgiFormat: dxgiFormat,
  77915. textureType: textureType
  77916. };
  77917. };
  77918. DDSTools._ToHalfFloat = function (value) {
  77919. if (!DDSTools._FloatView) {
  77920. DDSTools._FloatView = new Float32Array(1);
  77921. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77922. }
  77923. DDSTools._FloatView[0] = value;
  77924. var x = DDSTools._Int32View[0];
  77925. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77926. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77927. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77928. /* If zero, or denormal, or exponent underflows too much for a denormal
  77929. * half, return signed zero. */
  77930. if (e < 103) {
  77931. return bits;
  77932. }
  77933. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77934. if (e > 142) {
  77935. bits |= 0x7c00;
  77936. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77937. * not Inf, so make sure we set one mantissa bit too. */
  77938. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77939. return bits;
  77940. }
  77941. /* If exponent underflows but not too much, return a denormal */
  77942. if (e < 113) {
  77943. m |= 0x0800;
  77944. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77945. * to 1, which is OK. */
  77946. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77947. return bits;
  77948. }
  77949. bits |= ((e - 112) << 10) | (m >> 1);
  77950. bits += m & 1;
  77951. return bits;
  77952. };
  77953. DDSTools._FromHalfFloat = function (value) {
  77954. var s = (value & 0x8000) >> 15;
  77955. var e = (value & 0x7C00) >> 10;
  77956. var f = value & 0x03FF;
  77957. if (e === 0) {
  77958. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77959. }
  77960. else if (e == 0x1F) {
  77961. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77962. }
  77963. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77964. };
  77965. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77966. var destArray = new Float32Array(dataLength);
  77967. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77968. var index = 0;
  77969. for (var y = 0; y < height; y++) {
  77970. for (var x = 0; x < width; x++) {
  77971. var srcPos = (x + y * width) * 4;
  77972. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77973. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77974. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77975. if (DDSTools.StoreLODInAlphaChannel) {
  77976. destArray[index + 3] = lod;
  77977. }
  77978. else {
  77979. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77980. }
  77981. index += 4;
  77982. }
  77983. }
  77984. return destArray;
  77985. };
  77986. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77987. if (DDSTools.StoreLODInAlphaChannel) {
  77988. var destArray = new Uint16Array(dataLength);
  77989. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77990. var index = 0;
  77991. for (var y = 0; y < height; y++) {
  77992. for (var x = 0; x < width; x++) {
  77993. var srcPos = (x + y * width) * 4;
  77994. destArray[index] = srcData[srcPos];
  77995. destArray[index + 1] = srcData[srcPos + 1];
  77996. destArray[index + 2] = srcData[srcPos + 2];
  77997. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77998. index += 4;
  77999. }
  78000. }
  78001. return destArray;
  78002. }
  78003. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78004. };
  78005. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78006. if (DDSTools.StoreLODInAlphaChannel) {
  78007. var destArray = new Float32Array(dataLength);
  78008. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78009. var index = 0;
  78010. for (var y = 0; y < height; y++) {
  78011. for (var x = 0; x < width; x++) {
  78012. var srcPos = (x + y * width) * 4;
  78013. destArray[index] = srcData[srcPos];
  78014. destArray[index + 1] = srcData[srcPos + 1];
  78015. destArray[index + 2] = srcData[srcPos + 2];
  78016. destArray[index + 3] = lod;
  78017. index += 4;
  78018. }
  78019. }
  78020. return destArray;
  78021. }
  78022. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78023. };
  78024. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78025. var destArray = new Uint8Array(dataLength);
  78026. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78027. var index = 0;
  78028. for (var y = 0; y < height; y++) {
  78029. for (var x = 0; x < width; x++) {
  78030. var srcPos = (x + y * width) * 4;
  78031. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78032. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78033. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78034. if (DDSTools.StoreLODInAlphaChannel) {
  78035. destArray[index + 3] = lod;
  78036. }
  78037. else {
  78038. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78039. }
  78040. index += 4;
  78041. }
  78042. }
  78043. return destArray;
  78044. };
  78045. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78046. var destArray = new Uint8Array(dataLength);
  78047. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78048. var index = 0;
  78049. for (var y = 0; y < height; y++) {
  78050. for (var x = 0; x < width; x++) {
  78051. var srcPos = (x + y * width) * 4;
  78052. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78053. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78054. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78055. if (DDSTools.StoreLODInAlphaChannel) {
  78056. destArray[index + 3] = lod;
  78057. }
  78058. else {
  78059. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78060. }
  78061. index += 4;
  78062. }
  78063. }
  78064. return destArray;
  78065. };
  78066. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78067. var byteArray = new Uint8Array(dataLength);
  78068. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78069. var index = 0;
  78070. for (var y = 0; y < height; y++) {
  78071. for (var x = 0; x < width; x++) {
  78072. var srcPos = (x + y * width) * 4;
  78073. byteArray[index] = srcData[srcPos + rOffset];
  78074. byteArray[index + 1] = srcData[srcPos + gOffset];
  78075. byteArray[index + 2] = srcData[srcPos + bOffset];
  78076. byteArray[index + 3] = srcData[srcPos + aOffset];
  78077. index += 4;
  78078. }
  78079. }
  78080. return byteArray;
  78081. };
  78082. DDSTools._ExtractLongWordOrder = function (value) {
  78083. if (value === 0 || value === 255 || value === -16777216) {
  78084. return 0;
  78085. }
  78086. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78087. };
  78088. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78089. var byteArray = new Uint8Array(dataLength);
  78090. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78091. var index = 0;
  78092. for (var y = 0; y < height; y++) {
  78093. for (var x = 0; x < width; x++) {
  78094. var srcPos = (x + y * width) * 3;
  78095. byteArray[index] = srcData[srcPos + rOffset];
  78096. byteArray[index + 1] = srcData[srcPos + gOffset];
  78097. byteArray[index + 2] = srcData[srcPos + bOffset];
  78098. index += 3;
  78099. }
  78100. }
  78101. return byteArray;
  78102. };
  78103. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78104. var byteArray = new Uint8Array(dataLength);
  78105. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78106. var index = 0;
  78107. for (var y = 0; y < height; y++) {
  78108. for (var x = 0; x < width; x++) {
  78109. var srcPos = (x + y * width);
  78110. byteArray[index] = srcData[srcPos];
  78111. index++;
  78112. }
  78113. }
  78114. return byteArray;
  78115. };
  78116. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78117. if (lodIndex === void 0) { lodIndex = -1; }
  78118. var ext = engine.getCaps().s3tc;
  78119. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78120. var fourCC, width, height, dataLength = 0, dataOffset;
  78121. var byteArray, mipmapCount, mip;
  78122. var internalFormat = 0;
  78123. var format = 0;
  78124. var blockBytes = 1;
  78125. if (header[off_magic] !== DDS_MAGIC) {
  78126. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78127. return;
  78128. }
  78129. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78130. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78131. return;
  78132. }
  78133. if (info.isCompressed && !ext) {
  78134. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78135. return;
  78136. }
  78137. var bpp = header[off_RGBbpp];
  78138. dataOffset = header[off_size] + 4;
  78139. var computeFormats = false;
  78140. if (info.isFourCC) {
  78141. fourCC = header[off_pfFourCC];
  78142. switch (fourCC) {
  78143. case FOURCC_DXT1:
  78144. blockBytes = 8;
  78145. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78146. break;
  78147. case FOURCC_DXT3:
  78148. blockBytes = 16;
  78149. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78150. break;
  78151. case FOURCC_DXT5:
  78152. blockBytes = 16;
  78153. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78154. break;
  78155. case FOURCC_D3DFMT_R16G16B16A16F:
  78156. computeFormats = true;
  78157. break;
  78158. case FOURCC_D3DFMT_R32G32B32A32F:
  78159. computeFormats = true;
  78160. break;
  78161. case FOURCC_DX10:
  78162. // There is an additionnal header so dataOffset need to be changed
  78163. dataOffset += 5 * 4; // 5 uints
  78164. var supported = false;
  78165. switch (info.dxgiFormat) {
  78166. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78167. computeFormats = true;
  78168. supported = true;
  78169. break;
  78170. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78171. info.isRGB = true;
  78172. info.isFourCC = false;
  78173. bpp = 32;
  78174. supported = true;
  78175. break;
  78176. }
  78177. if (supported) {
  78178. break;
  78179. }
  78180. default:
  78181. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78182. return;
  78183. }
  78184. }
  78185. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78186. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78187. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78188. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78189. if (computeFormats) {
  78190. format = engine._getWebGLTextureType(info.textureType);
  78191. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78192. }
  78193. mipmapCount = 1;
  78194. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78195. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78196. }
  78197. for (var face = 0; face < faces; face++) {
  78198. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78199. width = header[off_width];
  78200. height = header[off_height];
  78201. for (mip = 0; mip < mipmapCount; ++mip) {
  78202. if (lodIndex === -1 || lodIndex === mip) {
  78203. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78204. var i = (lodIndex === -1) ? mip : 0;
  78205. if (!info.isCompressed && info.isFourCC) {
  78206. dataLength = width * height * 4;
  78207. var floatArray = null;
  78208. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78209. if (bpp === 128) {
  78210. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78211. }
  78212. else if (bpp === 64) {
  78213. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78214. }
  78215. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78216. format = engine._getWebGLTextureType(info.textureType);
  78217. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78218. }
  78219. else {
  78220. if (bpp === 128) {
  78221. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78222. }
  78223. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78224. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78225. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78226. format = engine._getWebGLTextureType(info.textureType);
  78227. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78228. }
  78229. else {
  78230. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78231. }
  78232. }
  78233. if (floatArray) {
  78234. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78235. }
  78236. }
  78237. else if (info.isRGB) {
  78238. if (bpp === 24) {
  78239. dataLength = width * height * 3;
  78240. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78241. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78242. }
  78243. else {
  78244. dataLength = width * height * 4;
  78245. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78246. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78247. }
  78248. }
  78249. else if (info.isLuminance) {
  78250. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78251. var unpaddedRowSize = width;
  78252. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78253. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78254. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78255. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78256. }
  78257. else {
  78258. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78259. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78260. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78261. }
  78262. }
  78263. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78264. width *= 0.5;
  78265. height *= 0.5;
  78266. width = Math.max(1.0, width);
  78267. height = Math.max(1.0, height);
  78268. }
  78269. if (currentFace !== undefined) {
  78270. // Loading a single face
  78271. break;
  78272. }
  78273. }
  78274. };
  78275. DDSTools.StoreLODInAlphaChannel = false;
  78276. return DDSTools;
  78277. }());
  78278. BABYLON.DDSTools = DDSTools;
  78279. })(BABYLON || (BABYLON = {}));
  78280. //# sourceMappingURL=babylon.dds.js.map
  78281. var BABYLON;
  78282. (function (BABYLON) {
  78283. /**
  78284. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78285. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78286. */
  78287. var KhronosTextureContainer = /** @class */ (function () {
  78288. /**
  78289. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78290. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78291. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78292. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78293. */
  78294. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78295. this.arrayBuffer = arrayBuffer;
  78296. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78297. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78298. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78299. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78300. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78301. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78302. BABYLON.Tools.Error("texture missing KTX identifier");
  78303. return;
  78304. }
  78305. // load the reset of the header in native 32 bit int
  78306. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78307. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78308. var oppositeEndianess = header[0] === 0x01020304;
  78309. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78310. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78311. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78312. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78313. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78314. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78315. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78316. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78317. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78318. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78319. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78320. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78321. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78322. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78323. if (this.glType !== 0) {
  78324. BABYLON.Tools.Error("only compressed formats currently supported");
  78325. return;
  78326. }
  78327. else {
  78328. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78329. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78330. }
  78331. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78332. BABYLON.Tools.Error("only 2D textures currently supported");
  78333. return;
  78334. }
  78335. if (this.numberOfArrayElements !== 0) {
  78336. BABYLON.Tools.Error("texture arrays not currently supported");
  78337. return;
  78338. }
  78339. if (this.numberOfFaces !== facesExpected) {
  78340. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78341. return;
  78342. }
  78343. // we now have a completely validated file, so could use existence of loadType as success
  78344. // would need to make this more elaborate & adjust checks above to support more than one load type
  78345. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78346. }
  78347. // not as fast hardware based, but will probably never need to use
  78348. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78349. return ((val & 0xFF) << 24)
  78350. | ((val & 0xFF00) << 8)
  78351. | ((val >> 8) & 0xFF00)
  78352. | ((val >> 24) & 0xFF);
  78353. };
  78354. /**
  78355. * It is assumed that the texture has already been created & is currently bound
  78356. */
  78357. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78358. switch (this.loadType) {
  78359. case KhronosTextureContainer.COMPRESSED_2D:
  78360. this._upload2DCompressedLevels(gl, loadMipmaps);
  78361. break;
  78362. case KhronosTextureContainer.TEX_2D:
  78363. case KhronosTextureContainer.COMPRESSED_3D:
  78364. case KhronosTextureContainer.TEX_3D:
  78365. }
  78366. };
  78367. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78368. // initialize width & height for level 1
  78369. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78370. var width = this.pixelWidth;
  78371. var height = this.pixelHeight;
  78372. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78373. for (var level = 0; level < mipmapCount; level++) {
  78374. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78375. for (var face = 0; face < this.numberOfFaces; face++) {
  78376. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78377. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78378. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78379. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78380. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78381. }
  78382. width = Math.max(1.0, width * 0.5);
  78383. height = Math.max(1.0, height * 0.5);
  78384. }
  78385. };
  78386. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78387. // load types
  78388. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78389. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78390. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78391. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78392. return KhronosTextureContainer;
  78393. }());
  78394. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78395. })(BABYLON || (BABYLON = {}));
  78396. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78397. var BABYLON;
  78398. (function (BABYLON) {
  78399. var Debug = /** @class */ (function () {
  78400. function Debug() {
  78401. }
  78402. Debug.AxesViewer = /** @class */ (function () {
  78403. function AxesViewer(scene, scaleLines) {
  78404. if (scaleLines === void 0) { scaleLines = 1; }
  78405. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78406. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78407. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78408. this.scaleLines = 1;
  78409. this.scaleLines = scaleLines;
  78410. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78411. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78412. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78413. this._xmesh.renderingGroupId = 2;
  78414. this._ymesh.renderingGroupId = 2;
  78415. this._zmesh.renderingGroupId = 2;
  78416. this._xmesh.material.checkReadyOnlyOnce = true;
  78417. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78418. this._ymesh.material.checkReadyOnlyOnce = true;
  78419. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78420. this._zmesh.material.checkReadyOnlyOnce = true;
  78421. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78422. this.scene = scene;
  78423. }
  78424. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78425. var scaleLines = this.scaleLines;
  78426. if (this._xmesh) {
  78427. this._xmesh.position.copyFrom(position);
  78428. }
  78429. if (this._ymesh) {
  78430. this._ymesh.position.copyFrom(position);
  78431. }
  78432. if (this._zmesh) {
  78433. this._zmesh.position.copyFrom(position);
  78434. }
  78435. var point2 = this._xline[1];
  78436. point2.x = xaxis.x * scaleLines;
  78437. point2.y = xaxis.y * scaleLines;
  78438. point2.z = xaxis.z * scaleLines;
  78439. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78440. point2 = this._yline[1];
  78441. point2.x = yaxis.x * scaleLines;
  78442. point2.y = yaxis.y * scaleLines;
  78443. point2.z = yaxis.z * scaleLines;
  78444. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78445. point2 = this._zline[1];
  78446. point2.x = zaxis.x * scaleLines;
  78447. point2.y = zaxis.y * scaleLines;
  78448. point2.z = zaxis.z * scaleLines;
  78449. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78450. };
  78451. AxesViewer.prototype.dispose = function () {
  78452. if (this._xmesh) {
  78453. this._xmesh.dispose();
  78454. }
  78455. if (this._ymesh) {
  78456. this._ymesh.dispose();
  78457. }
  78458. if (this._zmesh) {
  78459. this._zmesh.dispose();
  78460. }
  78461. this._xmesh = null;
  78462. this._ymesh = null;
  78463. this._zmesh = null;
  78464. this.scene = null;
  78465. };
  78466. return AxesViewer;
  78467. }());
  78468. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78469. __extends(BoneAxesViewer, _super);
  78470. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78471. if (scaleLines === void 0) { scaleLines = 1; }
  78472. var _this = _super.call(this, scene, scaleLines) || this;
  78473. _this.pos = BABYLON.Vector3.Zero();
  78474. _this.xaxis = BABYLON.Vector3.Zero();
  78475. _this.yaxis = BABYLON.Vector3.Zero();
  78476. _this.zaxis = BABYLON.Vector3.Zero();
  78477. _this.mesh = mesh;
  78478. _this.bone = bone;
  78479. return _this;
  78480. }
  78481. BoneAxesViewer.prototype.update = function () {
  78482. if (!this.mesh || !this.bone) {
  78483. return;
  78484. }
  78485. var bone = this.bone;
  78486. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78487. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78488. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78489. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78490. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78491. };
  78492. BoneAxesViewer.prototype.dispose = function () {
  78493. if (this.mesh) {
  78494. this.mesh = null;
  78495. this.bone = null;
  78496. _super.prototype.dispose.call(this);
  78497. }
  78498. };
  78499. return BoneAxesViewer;
  78500. }(Debug.AxesViewer));
  78501. Debug.PhysicsViewer = /** @class */ (function () {
  78502. function PhysicsViewer(scene) {
  78503. this._impostors = [];
  78504. this._meshes = [];
  78505. this._numMeshes = 0;
  78506. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78507. var physicEngine = this._scene.getPhysicsEngine();
  78508. if (physicEngine) {
  78509. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78510. }
  78511. }
  78512. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78513. var plugin = this._physicsEnginePlugin;
  78514. for (var i = 0; i < this._numMeshes; i++) {
  78515. var impostor = this._impostors[i];
  78516. if (!impostor) {
  78517. continue;
  78518. }
  78519. if (impostor.isDisposed) {
  78520. this.hideImpostor(this._impostors[i--]);
  78521. }
  78522. else {
  78523. var mesh = this._meshes[i];
  78524. if (mesh && plugin) {
  78525. plugin.syncMeshWithImpostor(mesh, impostor);
  78526. }
  78527. }
  78528. }
  78529. };
  78530. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78531. if (!this._scene) {
  78532. return;
  78533. }
  78534. for (var i = 0; i < this._numMeshes; i++) {
  78535. if (this._impostors[i] == impostor) {
  78536. return;
  78537. }
  78538. }
  78539. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78540. if (debugMesh) {
  78541. this._impostors[this._numMeshes] = impostor;
  78542. this._meshes[this._numMeshes] = debugMesh;
  78543. if (this._numMeshes === 0) {
  78544. this._renderFunction = this._updateDebugMeshes.bind(this);
  78545. this._scene.registerBeforeRender(this._renderFunction);
  78546. }
  78547. this._numMeshes++;
  78548. }
  78549. };
  78550. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78551. if (!impostor || !this._scene) {
  78552. return;
  78553. }
  78554. var removed = false;
  78555. for (var i = 0; i < this._numMeshes; i++) {
  78556. if (this._impostors[i] == impostor) {
  78557. var mesh = this._meshes[i];
  78558. if (!mesh) {
  78559. continue;
  78560. }
  78561. this._scene.removeMesh(mesh);
  78562. mesh.dispose();
  78563. this._numMeshes--;
  78564. if (this._numMeshes > 0) {
  78565. this._meshes[i] = this._meshes[this._numMeshes];
  78566. this._impostors[i] = this._impostors[this._numMeshes];
  78567. this._meshes[this._numMeshes] = null;
  78568. this._impostors[this._numMeshes] = null;
  78569. }
  78570. else {
  78571. this._meshes[0] = null;
  78572. this._impostors[0] = null;
  78573. }
  78574. removed = true;
  78575. break;
  78576. }
  78577. }
  78578. if (removed && this._numMeshes === 0) {
  78579. this._scene.unregisterBeforeRender(this._renderFunction);
  78580. }
  78581. };
  78582. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78583. if (!this._debugMaterial) {
  78584. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78585. this._debugMaterial.wireframe = true;
  78586. }
  78587. return this._debugMaterial;
  78588. };
  78589. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78590. if (!this._debugBoxMesh) {
  78591. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78592. this._debugBoxMesh.renderingGroupId = 1;
  78593. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78594. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78595. scene.removeMesh(this._debugBoxMesh);
  78596. }
  78597. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78598. };
  78599. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78600. if (!this._debugSphereMesh) {
  78601. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78602. this._debugSphereMesh.renderingGroupId = 1;
  78603. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78604. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78605. scene.removeMesh(this._debugSphereMesh);
  78606. }
  78607. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78608. };
  78609. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78610. var mesh = null;
  78611. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78612. mesh = this._getDebugBoxMesh(scene);
  78613. impostor.getBoxSizeToRef(mesh.scaling);
  78614. }
  78615. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78616. mesh = this._getDebugSphereMesh(scene);
  78617. var radius = impostor.getRadius();
  78618. mesh.scaling.x = radius * 2;
  78619. mesh.scaling.y = radius * 2;
  78620. mesh.scaling.z = radius * 2;
  78621. }
  78622. return mesh;
  78623. };
  78624. PhysicsViewer.prototype.dispose = function () {
  78625. for (var i = 0; i < this._numMeshes; i++) {
  78626. this.hideImpostor(this._impostors[i]);
  78627. }
  78628. if (this._debugBoxMesh) {
  78629. this._debugBoxMesh.dispose();
  78630. }
  78631. if (this._debugSphereMesh) {
  78632. this._debugSphereMesh.dispose();
  78633. }
  78634. if (this._debugMaterial) {
  78635. this._debugMaterial.dispose();
  78636. }
  78637. this._impostors.length = 0;
  78638. this._scene = null;
  78639. this._physicsEnginePlugin = null;
  78640. };
  78641. return PhysicsViewer;
  78642. }());
  78643. Debug.SkeletonViewer = /** @class */ (function () {
  78644. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78645. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78646. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78647. this.skeleton = skeleton;
  78648. this.mesh = mesh;
  78649. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78650. this.renderingGroupId = renderingGroupId;
  78651. this.color = BABYLON.Color3.White();
  78652. this._debugLines = new Array();
  78653. this._isEnabled = false;
  78654. this._scene = scene;
  78655. this.update();
  78656. this._renderFunction = this.update.bind(this);
  78657. }
  78658. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78659. get: function () {
  78660. return this._isEnabled;
  78661. },
  78662. set: function (value) {
  78663. if (this._isEnabled === value) {
  78664. return;
  78665. }
  78666. this._isEnabled = value;
  78667. if (value) {
  78668. this._scene.registerBeforeRender(this._renderFunction);
  78669. }
  78670. else {
  78671. this._scene.unregisterBeforeRender(this._renderFunction);
  78672. }
  78673. },
  78674. enumerable: true,
  78675. configurable: true
  78676. });
  78677. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78678. if (x === void 0) { x = 0; }
  78679. if (y === void 0) { y = 0; }
  78680. if (z === void 0) { z = 0; }
  78681. var tmat = BABYLON.Tmp.Matrix[0];
  78682. var parentBone = bone.getParent();
  78683. tmat.copyFrom(bone.getLocalMatrix());
  78684. if (x !== 0 || y !== 0 || z !== 0) {
  78685. var tmat2 = BABYLON.Tmp.Matrix[1];
  78686. BABYLON.Matrix.IdentityToRef(tmat2);
  78687. tmat2.m[12] = x;
  78688. tmat2.m[13] = y;
  78689. tmat2.m[14] = z;
  78690. tmat2.multiplyToRef(tmat, tmat);
  78691. }
  78692. if (parentBone) {
  78693. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78694. }
  78695. tmat.multiplyToRef(meshMat, tmat);
  78696. position.x = tmat.m[12];
  78697. position.y = tmat.m[13];
  78698. position.z = tmat.m[14];
  78699. };
  78700. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78701. var len = bones.length;
  78702. var meshPos = this.mesh.position;
  78703. for (var i = 0; i < len; i++) {
  78704. var bone = bones[i];
  78705. var points = this._debugLines[i];
  78706. if (!points) {
  78707. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78708. this._debugLines[i] = points;
  78709. }
  78710. this._getBonePosition(points[0], bone, meshMat);
  78711. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78712. points[0].subtractInPlace(meshPos);
  78713. points[1].subtractInPlace(meshPos);
  78714. }
  78715. };
  78716. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78717. var len = bones.length;
  78718. var boneNum = 0;
  78719. var meshPos = this.mesh.position;
  78720. for (var i = len - 1; i >= 0; i--) {
  78721. var childBone = bones[i];
  78722. var parentBone = childBone.getParent();
  78723. if (!parentBone) {
  78724. continue;
  78725. }
  78726. var points = this._debugLines[boneNum];
  78727. if (!points) {
  78728. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78729. this._debugLines[boneNum] = points;
  78730. }
  78731. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78732. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78733. points[0].subtractInPlace(meshPos);
  78734. points[1].subtractInPlace(meshPos);
  78735. boneNum++;
  78736. }
  78737. };
  78738. SkeletonViewer.prototype.update = function () {
  78739. if (this.autoUpdateBonesMatrices) {
  78740. this.skeleton.computeAbsoluteTransforms();
  78741. }
  78742. if (this.skeleton.bones[0].length === undefined) {
  78743. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78744. }
  78745. else {
  78746. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78747. }
  78748. if (!this._debugMesh) {
  78749. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78750. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78751. }
  78752. else {
  78753. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78754. }
  78755. this._debugMesh.position.copyFrom(this.mesh.position);
  78756. this._debugMesh.color = this.color;
  78757. };
  78758. SkeletonViewer.prototype.dispose = function () {
  78759. if (this._debugMesh) {
  78760. this.isEnabled = false;
  78761. this._debugMesh.dispose();
  78762. this._debugMesh = null;
  78763. }
  78764. };
  78765. return SkeletonViewer;
  78766. }());
  78767. return Debug;
  78768. }());
  78769. BABYLON.Debug = Debug;
  78770. })(BABYLON || (BABYLON = {}));
  78771. //# sourceMappingURL=babylon.debugModules.js.map
  78772. var BABYLON;
  78773. (function (BABYLON) {
  78774. var RayHelper = /** @class */ (function () {
  78775. function RayHelper(ray) {
  78776. this.ray = ray;
  78777. }
  78778. RayHelper.CreateAndShow = function (ray, scene, color) {
  78779. var helper = new RayHelper(ray);
  78780. helper.show(scene, color);
  78781. return helper;
  78782. };
  78783. RayHelper.prototype.show = function (scene, color) {
  78784. if (!this._renderFunction && this.ray) {
  78785. var ray = this.ray;
  78786. this._renderFunction = this._render.bind(this);
  78787. this._scene = scene;
  78788. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78789. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78790. if (this._renderFunction) {
  78791. this._scene.registerBeforeRender(this._renderFunction);
  78792. }
  78793. }
  78794. if (color && this._renderLine) {
  78795. this._renderLine.color.copyFrom(color);
  78796. }
  78797. };
  78798. RayHelper.prototype.hide = function () {
  78799. if (this._renderFunction && this._scene) {
  78800. this._scene.unregisterBeforeRender(this._renderFunction);
  78801. this._scene = null;
  78802. this._renderFunction = null;
  78803. if (this._renderLine) {
  78804. this._renderLine.dispose();
  78805. this._renderLine = null;
  78806. }
  78807. this._renderPoints = [];
  78808. }
  78809. };
  78810. RayHelper.prototype._render = function () {
  78811. var ray = this.ray;
  78812. if (!ray) {
  78813. return;
  78814. }
  78815. var point = this._renderPoints[1];
  78816. var len = Math.min(ray.length, 1000000);
  78817. point.copyFrom(ray.direction);
  78818. point.scaleInPlace(len);
  78819. point.addInPlace(ray.origin);
  78820. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78821. };
  78822. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78823. this._attachedToMesh = mesh;
  78824. var ray = this.ray;
  78825. if (!ray) {
  78826. return;
  78827. }
  78828. if (!ray.direction) {
  78829. ray.direction = BABYLON.Vector3.Zero();
  78830. }
  78831. if (!ray.origin) {
  78832. ray.origin = BABYLON.Vector3.Zero();
  78833. }
  78834. if (length) {
  78835. ray.length = length;
  78836. }
  78837. if (!meshSpaceOrigin) {
  78838. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78839. }
  78840. if (!meshSpaceDirection) {
  78841. // -1 so that this will work with Mesh.lookAt
  78842. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78843. }
  78844. if (!this._meshSpaceDirection) {
  78845. this._meshSpaceDirection = meshSpaceDirection.clone();
  78846. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78847. }
  78848. else {
  78849. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78850. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78851. }
  78852. if (!this._updateToMeshFunction) {
  78853. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78854. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78855. }
  78856. this._updateToMesh();
  78857. };
  78858. RayHelper.prototype.detachFromMesh = function () {
  78859. if (this._attachedToMesh) {
  78860. if (this._updateToMeshFunction) {
  78861. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78862. }
  78863. this._attachedToMesh = null;
  78864. this._updateToMeshFunction = null;
  78865. }
  78866. };
  78867. RayHelper.prototype._updateToMesh = function () {
  78868. var ray = this.ray;
  78869. if (!this._attachedToMesh || !ray) {
  78870. return;
  78871. }
  78872. if (this._attachedToMesh._isDisposed) {
  78873. this.detachFromMesh();
  78874. return;
  78875. }
  78876. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78877. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78878. };
  78879. RayHelper.prototype.dispose = function () {
  78880. this.hide();
  78881. this.detachFromMesh();
  78882. this.ray = null;
  78883. };
  78884. return RayHelper;
  78885. }());
  78886. BABYLON.RayHelper = RayHelper;
  78887. })(BABYLON || (BABYLON = {}));
  78888. //# sourceMappingURL=babylon.rayHelper.js.map
  78889. var BABYLON;
  78890. (function (BABYLON) {
  78891. // load the inspector using require, if not present in the global namespace.
  78892. var DebugLayer = /** @class */ (function () {
  78893. function DebugLayer(scene) {
  78894. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78895. this._scene = scene;
  78896. // load inspector using require, if it doesn't exist on the global namespace.
  78897. }
  78898. /** Creates the inspector window. */
  78899. DebugLayer.prototype._createInspector = function (config) {
  78900. if (config === void 0) { config = {}; }
  78901. var popup = config.popup || false;
  78902. var initialTab = config.initialTab || 0;
  78903. var parentElement = config.parentElement || null;
  78904. if (!this._inspector) {
  78905. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78906. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78907. } // else nothing to do,; instance is already existing
  78908. };
  78909. DebugLayer.prototype.isVisible = function () {
  78910. if (!this._inspector) {
  78911. return false;
  78912. }
  78913. return true;
  78914. };
  78915. DebugLayer.prototype.hide = function () {
  78916. if (this._inspector) {
  78917. try {
  78918. this._inspector.dispose();
  78919. }
  78920. catch (e) {
  78921. // If the inspector has been removed directly from the inspector tool
  78922. }
  78923. this._inspector = null;
  78924. }
  78925. };
  78926. DebugLayer.prototype.show = function (config) {
  78927. if (config === void 0) { config = {}; }
  78928. if (typeof this.BJSINSPECTOR == 'undefined') {
  78929. // Load inspector and add it to the DOM
  78930. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78931. }
  78932. else {
  78933. // Otherwise creates the inspector
  78934. this._createInspector(config);
  78935. }
  78936. };
  78937. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78938. return DebugLayer;
  78939. }());
  78940. BABYLON.DebugLayer = DebugLayer;
  78941. })(BABYLON || (BABYLON = {}));
  78942. //# sourceMappingURL=babylon.debugLayer.js.map
  78943. var BABYLON;
  78944. (function (BABYLON) {
  78945. var BoundingBoxRenderer = /** @class */ (function () {
  78946. function BoundingBoxRenderer(scene) {
  78947. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78948. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78949. this.showBackLines = true;
  78950. this.renderList = new BABYLON.SmartArray(32);
  78951. this._vertexBuffers = {};
  78952. this._scene = scene;
  78953. }
  78954. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78955. if (this._colorShader) {
  78956. return;
  78957. }
  78958. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78959. attributes: [BABYLON.VertexBuffer.PositionKind],
  78960. uniforms: ["world", "viewProjection", "color"]
  78961. });
  78962. var engine = this._scene.getEngine();
  78963. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78964. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78965. this._createIndexBuffer();
  78966. };
  78967. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78968. var engine = this._scene.getEngine();
  78969. 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]);
  78970. };
  78971. BoundingBoxRenderer.prototype._rebuild = function () {
  78972. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78973. if (vb) {
  78974. vb._rebuild();
  78975. }
  78976. this._createIndexBuffer();
  78977. };
  78978. BoundingBoxRenderer.prototype.reset = function () {
  78979. this.renderList.reset();
  78980. };
  78981. BoundingBoxRenderer.prototype.render = function () {
  78982. if (this.renderList.length === 0) {
  78983. return;
  78984. }
  78985. this._prepareRessources();
  78986. if (!this._colorShader.isReady()) {
  78987. return;
  78988. }
  78989. var engine = this._scene.getEngine();
  78990. engine.setDepthWrite(false);
  78991. this._colorShader._preBind();
  78992. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78993. var boundingBox = this.renderList.data[boundingBoxIndex];
  78994. var min = boundingBox.minimum;
  78995. var max = boundingBox.maximum;
  78996. var diff = max.subtract(min);
  78997. var median = min.add(diff.scale(0.5));
  78998. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78999. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79000. .multiply(boundingBox.getWorldMatrix());
  79001. // VBOs
  79002. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79003. if (this.showBackLines) {
  79004. // Back
  79005. engine.setDepthFunctionToGreaterOrEqual();
  79006. this._scene.resetCachedMaterial();
  79007. this._colorShader.setColor4("color", this.backColor.toColor4());
  79008. this._colorShader.bind(worldMatrix);
  79009. // Draw order
  79010. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79011. }
  79012. // Front
  79013. engine.setDepthFunctionToLess();
  79014. this._scene.resetCachedMaterial();
  79015. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79016. this._colorShader.bind(worldMatrix);
  79017. // Draw order
  79018. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79019. }
  79020. this._colorShader.unbind();
  79021. engine.setDepthFunctionToLessOrEqual();
  79022. engine.setDepthWrite(true);
  79023. };
  79024. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79025. this._prepareRessources();
  79026. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79027. return;
  79028. }
  79029. var engine = this._scene.getEngine();
  79030. engine.setDepthWrite(false);
  79031. engine.setColorWrite(false);
  79032. this._colorShader._preBind();
  79033. var boundingBox = mesh._boundingInfo.boundingBox;
  79034. var min = boundingBox.minimum;
  79035. var max = boundingBox.maximum;
  79036. var diff = max.subtract(min);
  79037. var median = min.add(diff.scale(0.5));
  79038. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79039. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79040. .multiply(boundingBox.getWorldMatrix());
  79041. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79042. engine.setDepthFunctionToLess();
  79043. this._scene.resetCachedMaterial();
  79044. this._colorShader.bind(worldMatrix);
  79045. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79046. this._colorShader.unbind();
  79047. engine.setDepthFunctionToLessOrEqual();
  79048. engine.setDepthWrite(true);
  79049. engine.setColorWrite(true);
  79050. };
  79051. BoundingBoxRenderer.prototype.dispose = function () {
  79052. if (!this._colorShader) {
  79053. return;
  79054. }
  79055. this.renderList.dispose();
  79056. this._colorShader.dispose();
  79057. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79058. if (buffer) {
  79059. buffer.dispose();
  79060. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79061. }
  79062. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79063. };
  79064. return BoundingBoxRenderer;
  79065. }());
  79066. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79067. })(BABYLON || (BABYLON = {}));
  79068. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79069. var BABYLON;
  79070. (function (BABYLON) {
  79071. var MorphTarget = /** @class */ (function () {
  79072. function MorphTarget(name, influence) {
  79073. if (influence === void 0) { influence = 0; }
  79074. this.name = name;
  79075. this.animations = new Array();
  79076. this._positions = null;
  79077. this._normals = null;
  79078. this._tangents = null;
  79079. this.onInfluenceChanged = new BABYLON.Observable();
  79080. this.influence = influence;
  79081. }
  79082. Object.defineProperty(MorphTarget.prototype, "influence", {
  79083. get: function () {
  79084. return this._influence;
  79085. },
  79086. set: function (influence) {
  79087. if (this._influence === influence) {
  79088. return;
  79089. }
  79090. var previous = this._influence;
  79091. this._influence = influence;
  79092. if (this.onInfluenceChanged.hasObservers) {
  79093. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79094. }
  79095. },
  79096. enumerable: true,
  79097. configurable: true
  79098. });
  79099. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79100. get: function () {
  79101. return !!this._positions;
  79102. },
  79103. enumerable: true,
  79104. configurable: true
  79105. });
  79106. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79107. get: function () {
  79108. return !!this._normals;
  79109. },
  79110. enumerable: true,
  79111. configurable: true
  79112. });
  79113. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79114. get: function () {
  79115. return !!this._tangents;
  79116. },
  79117. enumerable: true,
  79118. configurable: true
  79119. });
  79120. MorphTarget.prototype.setPositions = function (data) {
  79121. this._positions = data;
  79122. };
  79123. MorphTarget.prototype.getPositions = function () {
  79124. return this._positions;
  79125. };
  79126. MorphTarget.prototype.setNormals = function (data) {
  79127. this._normals = data;
  79128. };
  79129. MorphTarget.prototype.getNormals = function () {
  79130. return this._normals;
  79131. };
  79132. MorphTarget.prototype.setTangents = function (data) {
  79133. this._tangents = data;
  79134. };
  79135. MorphTarget.prototype.getTangents = function () {
  79136. return this._tangents;
  79137. };
  79138. /**
  79139. * Serializes the current target into a Serialization object.
  79140. * Returns the serialized object.
  79141. */
  79142. MorphTarget.prototype.serialize = function () {
  79143. var serializationObject = {};
  79144. serializationObject.name = this.name;
  79145. serializationObject.influence = this.influence;
  79146. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79147. if (this.hasNormals) {
  79148. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79149. }
  79150. if (this.hasTangents) {
  79151. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79152. }
  79153. // Animations
  79154. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79155. return serializationObject;
  79156. };
  79157. // Statics
  79158. MorphTarget.Parse = function (serializationObject) {
  79159. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79160. result.setPositions(serializationObject.positions);
  79161. if (serializationObject.normals) {
  79162. result.setNormals(serializationObject.normals);
  79163. }
  79164. if (serializationObject.tangents) {
  79165. result.setTangents(serializationObject.tangents);
  79166. }
  79167. // Animations
  79168. if (serializationObject.animations) {
  79169. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79170. var parsedAnimation = serializationObject.animations[animationIndex];
  79171. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79172. }
  79173. }
  79174. return result;
  79175. };
  79176. MorphTarget.FromMesh = function (mesh, name, influence) {
  79177. if (!name) {
  79178. name = mesh.name;
  79179. }
  79180. var result = new MorphTarget(name, influence);
  79181. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79182. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79183. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79184. }
  79185. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79186. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79187. }
  79188. return result;
  79189. };
  79190. return MorphTarget;
  79191. }());
  79192. BABYLON.MorphTarget = MorphTarget;
  79193. })(BABYLON || (BABYLON = {}));
  79194. //# sourceMappingURL=babylon.morphTarget.js.map
  79195. var BABYLON;
  79196. (function (BABYLON) {
  79197. var MorphTargetManager = /** @class */ (function () {
  79198. function MorphTargetManager(scene) {
  79199. if (scene === void 0) { scene = null; }
  79200. this._targets = new Array();
  79201. this._targetObservable = new Array();
  79202. this._activeTargets = new BABYLON.SmartArray(16);
  79203. this._supportsNormals = false;
  79204. this._supportsTangents = false;
  79205. this._vertexCount = 0;
  79206. this._uniqueId = 0;
  79207. this._tempInfluences = new Array();
  79208. if (!scene) {
  79209. scene = BABYLON.Engine.LastCreatedScene;
  79210. }
  79211. this._scene = scene;
  79212. if (this._scene) {
  79213. this._scene.morphTargetManagers.push(this);
  79214. this._uniqueId = this._scene.getUniqueId();
  79215. }
  79216. }
  79217. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79218. get: function () {
  79219. return this._uniqueId;
  79220. },
  79221. enumerable: true,
  79222. configurable: true
  79223. });
  79224. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79225. get: function () {
  79226. return this._vertexCount;
  79227. },
  79228. enumerable: true,
  79229. configurable: true
  79230. });
  79231. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79232. get: function () {
  79233. return this._supportsNormals;
  79234. },
  79235. enumerable: true,
  79236. configurable: true
  79237. });
  79238. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79239. get: function () {
  79240. return this._supportsTangents;
  79241. },
  79242. enumerable: true,
  79243. configurable: true
  79244. });
  79245. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79246. get: function () {
  79247. return this._targets.length;
  79248. },
  79249. enumerable: true,
  79250. configurable: true
  79251. });
  79252. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79253. get: function () {
  79254. return this._activeTargets.length;
  79255. },
  79256. enumerable: true,
  79257. configurable: true
  79258. });
  79259. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79260. get: function () {
  79261. return this._influences;
  79262. },
  79263. enumerable: true,
  79264. configurable: true
  79265. });
  79266. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79267. return this._activeTargets.data[index];
  79268. };
  79269. MorphTargetManager.prototype.getTarget = function (index) {
  79270. return this._targets[index];
  79271. };
  79272. MorphTargetManager.prototype.addTarget = function (target) {
  79273. var _this = this;
  79274. this._targets.push(target);
  79275. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79276. _this._syncActiveTargets(needUpdate);
  79277. }));
  79278. this._syncActiveTargets(true);
  79279. };
  79280. MorphTargetManager.prototype.removeTarget = function (target) {
  79281. var index = this._targets.indexOf(target);
  79282. if (index >= 0) {
  79283. this._targets.splice(index, 1);
  79284. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79285. this._syncActiveTargets(true);
  79286. }
  79287. };
  79288. /**
  79289. * Serializes the current manager into a Serialization object.
  79290. * Returns the serialized object.
  79291. */
  79292. MorphTargetManager.prototype.serialize = function () {
  79293. var serializationObject = {};
  79294. serializationObject.id = this.uniqueId;
  79295. serializationObject.targets = [];
  79296. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79297. var target = _a[_i];
  79298. serializationObject.targets.push(target.serialize());
  79299. }
  79300. return serializationObject;
  79301. };
  79302. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79303. var influenceCount = 0;
  79304. this._activeTargets.reset();
  79305. this._supportsNormals = true;
  79306. this._supportsTangents = true;
  79307. this._vertexCount = 0;
  79308. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79309. var target = _a[_i];
  79310. this._activeTargets.push(target);
  79311. this._tempInfluences[influenceCount++] = target.influence;
  79312. var positions = target.getPositions();
  79313. if (positions) {
  79314. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79315. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79316. var vertexCount = positions.length / 3;
  79317. if (this._vertexCount === 0) {
  79318. this._vertexCount = vertexCount;
  79319. }
  79320. else if (this._vertexCount !== vertexCount) {
  79321. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79322. return;
  79323. }
  79324. }
  79325. }
  79326. if (!this._influences || this._influences.length !== influenceCount) {
  79327. this._influences = new Float32Array(influenceCount);
  79328. }
  79329. for (var index = 0; index < influenceCount; index++) {
  79330. this._influences[index] = this._tempInfluences[index];
  79331. }
  79332. if (needUpdate && this._scene) {
  79333. // Flag meshes as dirty to resync with the active targets
  79334. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79335. var mesh = _c[_b];
  79336. if (mesh.morphTargetManager === this) {
  79337. mesh._syncGeometryWithMorphTargetManager();
  79338. }
  79339. }
  79340. }
  79341. };
  79342. // Statics
  79343. MorphTargetManager.Parse = function (serializationObject, scene) {
  79344. var result = new MorphTargetManager(scene);
  79345. result._uniqueId = serializationObject.id;
  79346. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79347. var targetData = _a[_i];
  79348. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79349. }
  79350. return result;
  79351. };
  79352. return MorphTargetManager;
  79353. }());
  79354. BABYLON.MorphTargetManager = MorphTargetManager;
  79355. })(BABYLON || (BABYLON = {}));
  79356. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79357. var BABYLON;
  79358. (function (BABYLON) {
  79359. var Octree = /** @class */ (function () {
  79360. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79361. if (maxDepth === void 0) { maxDepth = 2; }
  79362. this.maxDepth = maxDepth;
  79363. this.dynamicContent = new Array();
  79364. this._maxBlockCapacity = maxBlockCapacity || 64;
  79365. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79366. this._creationFunc = creationFunc;
  79367. }
  79368. // Methods
  79369. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79370. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79371. };
  79372. Octree.prototype.addMesh = function (entry) {
  79373. for (var index = 0; index < this.blocks.length; index++) {
  79374. var block = this.blocks[index];
  79375. block.addEntry(entry);
  79376. }
  79377. };
  79378. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79379. this._selectionContent.reset();
  79380. for (var index = 0; index < this.blocks.length; index++) {
  79381. var block = this.blocks[index];
  79382. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79383. }
  79384. if (allowDuplicate) {
  79385. this._selectionContent.concat(this.dynamicContent);
  79386. }
  79387. else {
  79388. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79389. }
  79390. return this._selectionContent;
  79391. };
  79392. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79393. this._selectionContent.reset();
  79394. for (var index = 0; index < this.blocks.length; index++) {
  79395. var block = this.blocks[index];
  79396. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79397. }
  79398. if (allowDuplicate) {
  79399. this._selectionContent.concat(this.dynamicContent);
  79400. }
  79401. else {
  79402. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79403. }
  79404. return this._selectionContent;
  79405. };
  79406. Octree.prototype.intersectsRay = function (ray) {
  79407. this._selectionContent.reset();
  79408. for (var index = 0; index < this.blocks.length; index++) {
  79409. var block = this.blocks[index];
  79410. block.intersectsRay(ray, this._selectionContent);
  79411. }
  79412. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79413. return this._selectionContent;
  79414. };
  79415. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79416. target.blocks = new Array();
  79417. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79418. // Segmenting space
  79419. for (var x = 0; x < 2; x++) {
  79420. for (var y = 0; y < 2; y++) {
  79421. for (var z = 0; z < 2; z++) {
  79422. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79423. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79424. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79425. block.addEntries(entries);
  79426. target.blocks.push(block);
  79427. }
  79428. }
  79429. }
  79430. };
  79431. Octree.CreationFuncForMeshes = function (entry, block) {
  79432. var boundingInfo = entry.getBoundingInfo();
  79433. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79434. block.entries.push(entry);
  79435. }
  79436. };
  79437. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79438. var boundingInfo = entry.getBoundingInfo();
  79439. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79440. block.entries.push(entry);
  79441. }
  79442. };
  79443. return Octree;
  79444. }());
  79445. BABYLON.Octree = Octree;
  79446. })(BABYLON || (BABYLON = {}));
  79447. //# sourceMappingURL=babylon.octree.js.map
  79448. var BABYLON;
  79449. (function (BABYLON) {
  79450. var OctreeBlock = /** @class */ (function () {
  79451. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79452. this.entries = new Array();
  79453. this._boundingVectors = new Array();
  79454. this._capacity = capacity;
  79455. this._depth = depth;
  79456. this._maxDepth = maxDepth;
  79457. this._creationFunc = creationFunc;
  79458. this._minPoint = minPoint;
  79459. this._maxPoint = maxPoint;
  79460. this._boundingVectors.push(minPoint.clone());
  79461. this._boundingVectors.push(maxPoint.clone());
  79462. this._boundingVectors.push(minPoint.clone());
  79463. this._boundingVectors[2].x = maxPoint.x;
  79464. this._boundingVectors.push(minPoint.clone());
  79465. this._boundingVectors[3].y = maxPoint.y;
  79466. this._boundingVectors.push(minPoint.clone());
  79467. this._boundingVectors[4].z = maxPoint.z;
  79468. this._boundingVectors.push(maxPoint.clone());
  79469. this._boundingVectors[5].z = minPoint.z;
  79470. this._boundingVectors.push(maxPoint.clone());
  79471. this._boundingVectors[6].x = minPoint.x;
  79472. this._boundingVectors.push(maxPoint.clone());
  79473. this._boundingVectors[7].y = minPoint.y;
  79474. }
  79475. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79476. // Property
  79477. get: function () {
  79478. return this._capacity;
  79479. },
  79480. enumerable: true,
  79481. configurable: true
  79482. });
  79483. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79484. get: function () {
  79485. return this._minPoint;
  79486. },
  79487. enumerable: true,
  79488. configurable: true
  79489. });
  79490. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79491. get: function () {
  79492. return this._maxPoint;
  79493. },
  79494. enumerable: true,
  79495. configurable: true
  79496. });
  79497. // Methods
  79498. OctreeBlock.prototype.addEntry = function (entry) {
  79499. if (this.blocks) {
  79500. for (var index = 0; index < this.blocks.length; index++) {
  79501. var block = this.blocks[index];
  79502. block.addEntry(entry);
  79503. }
  79504. return;
  79505. }
  79506. this._creationFunc(entry, this);
  79507. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79508. this.createInnerBlocks();
  79509. }
  79510. };
  79511. OctreeBlock.prototype.addEntries = function (entries) {
  79512. for (var index = 0; index < entries.length; index++) {
  79513. var mesh = entries[index];
  79514. this.addEntry(mesh);
  79515. }
  79516. };
  79517. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79518. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79519. if (this.blocks) {
  79520. for (var index = 0; index < this.blocks.length; index++) {
  79521. var block = this.blocks[index];
  79522. block.select(frustumPlanes, selection, allowDuplicate);
  79523. }
  79524. return;
  79525. }
  79526. if (allowDuplicate) {
  79527. selection.concat(this.entries);
  79528. }
  79529. else {
  79530. selection.concatWithNoDuplicate(this.entries);
  79531. }
  79532. }
  79533. };
  79534. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79535. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79536. if (this.blocks) {
  79537. for (var index = 0; index < this.blocks.length; index++) {
  79538. var block = this.blocks[index];
  79539. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79540. }
  79541. return;
  79542. }
  79543. if (allowDuplicate) {
  79544. selection.concat(this.entries);
  79545. }
  79546. else {
  79547. selection.concatWithNoDuplicate(this.entries);
  79548. }
  79549. }
  79550. };
  79551. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79552. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79553. if (this.blocks) {
  79554. for (var index = 0; index < this.blocks.length; index++) {
  79555. var block = this.blocks[index];
  79556. block.intersectsRay(ray, selection);
  79557. }
  79558. return;
  79559. }
  79560. selection.concatWithNoDuplicate(this.entries);
  79561. }
  79562. };
  79563. OctreeBlock.prototype.createInnerBlocks = function () {
  79564. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79565. };
  79566. return OctreeBlock;
  79567. }());
  79568. BABYLON.OctreeBlock = OctreeBlock;
  79569. })(BABYLON || (BABYLON = {}));
  79570. //# sourceMappingURL=babylon.octreeBlock.js.map
  79571. var BABYLON;
  79572. (function (BABYLON) {
  79573. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79574. __extends(VRDistortionCorrectionPostProcess, _super);
  79575. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79576. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79577. 'LensCenter',
  79578. 'Scale',
  79579. 'ScaleIn',
  79580. 'HmdWarpParam'
  79581. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79582. _this._isRightEye = isRightEye;
  79583. _this._distortionFactors = vrMetrics.distortionK;
  79584. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79585. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79586. _this.adaptScaleToCurrentViewport = true;
  79587. _this.onSizeChangedObservable.add(function () {
  79588. _this.aspectRatio = _this.width * .5 / _this.height;
  79589. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79590. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79591. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79592. });
  79593. _this.onApplyObservable.add(function (effect) {
  79594. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79595. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79596. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79597. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79598. });
  79599. return _this;
  79600. }
  79601. return VRDistortionCorrectionPostProcess;
  79602. }(BABYLON.PostProcess));
  79603. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79604. })(BABYLON || (BABYLON = {}));
  79605. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79606. var BABYLON;
  79607. (function (BABYLON) {
  79608. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79609. __extends(AnaglyphPostProcess, _super);
  79610. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79611. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79612. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79613. _this.onApplyObservable.add(function (effect) {
  79614. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79615. });
  79616. return _this;
  79617. }
  79618. return AnaglyphPostProcess;
  79619. }(BABYLON.PostProcess));
  79620. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79621. })(BABYLON || (BABYLON = {}));
  79622. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79623. var BABYLON;
  79624. (function (BABYLON) {
  79625. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79626. __extends(StereoscopicInterlacePostProcess, _super);
  79627. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79628. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79629. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79630. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79631. _this.onSizeChangedObservable.add(function () {
  79632. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79633. });
  79634. _this.onApplyObservable.add(function (effect) {
  79635. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79636. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79637. });
  79638. return _this;
  79639. }
  79640. return StereoscopicInterlacePostProcess;
  79641. }(BABYLON.PostProcess));
  79642. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79643. })(BABYLON || (BABYLON = {}));
  79644. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79645. var BABYLON;
  79646. (function (BABYLON) {
  79647. /**
  79648. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79649. * Screen rotation is taken into account.
  79650. */
  79651. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79652. function FreeCameraDeviceOrientationInput() {
  79653. var _this = this;
  79654. this._screenOrientationAngle = 0;
  79655. this._screenQuaternion = new BABYLON.Quaternion();
  79656. this._alpha = 0;
  79657. this._beta = 0;
  79658. this._gamma = 0;
  79659. this._orientationChanged = function () {
  79660. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79661. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79662. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79663. };
  79664. this._deviceOrientation = function (evt) {
  79665. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79666. _this._beta = evt.beta !== null ? evt.beta : 0;
  79667. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79668. };
  79669. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79670. this._orientationChanged();
  79671. }
  79672. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79673. get: function () {
  79674. return this._camera;
  79675. },
  79676. set: function (camera) {
  79677. this._camera = camera;
  79678. if (this._camera != null && !this._camera.rotationQuaternion) {
  79679. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79680. }
  79681. },
  79682. enumerable: true,
  79683. configurable: true
  79684. });
  79685. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79686. window.addEventListener("orientationchange", this._orientationChanged);
  79687. window.addEventListener("deviceorientation", this._deviceOrientation);
  79688. //In certain cases, the attach control is called AFTER orientation was changed,
  79689. //So this is needed.
  79690. this._orientationChanged();
  79691. };
  79692. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79693. window.removeEventListener("orientationchange", this._orientationChanged);
  79694. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79695. };
  79696. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79697. //if no device orientation provided, don't update the rotation.
  79698. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79699. if (!this._alpha)
  79700. return;
  79701. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79702. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79703. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79704. //Mirror on XY Plane
  79705. this._camera.rotationQuaternion.z *= -1;
  79706. this._camera.rotationQuaternion.w *= -1;
  79707. };
  79708. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79709. return "FreeCameraDeviceOrientationInput";
  79710. };
  79711. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79712. return "deviceOrientation";
  79713. };
  79714. return FreeCameraDeviceOrientationInput;
  79715. }());
  79716. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79717. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79718. })(BABYLON || (BABYLON = {}));
  79719. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79720. var BABYLON;
  79721. (function (BABYLON) {
  79722. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79723. function ArcRotateCameraVRDeviceOrientationInput() {
  79724. this.alphaCorrection = 1;
  79725. this.betaCorrection = 1;
  79726. this.gammaCorrection = 1;
  79727. this._alpha = 0;
  79728. this._gamma = 0;
  79729. this._dirty = false;
  79730. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79731. }
  79732. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79733. this.camera.attachControl(element, noPreventDefault);
  79734. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79735. };
  79736. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79737. if (evt.alpha !== null) {
  79738. this._alpha = +evt.alpha | 0;
  79739. }
  79740. if (evt.gamma !== null) {
  79741. this._gamma = +evt.gamma | 0;
  79742. }
  79743. this._dirty = true;
  79744. };
  79745. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79746. if (this._dirty) {
  79747. this._dirty = false;
  79748. if (this._gamma < 0) {
  79749. this._gamma = 180 + this._gamma;
  79750. }
  79751. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79752. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79753. }
  79754. };
  79755. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79756. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79757. };
  79758. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79759. return "ArcRotateCameraVRDeviceOrientationInput";
  79760. };
  79761. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79762. return "VRDeviceOrientation";
  79763. };
  79764. return ArcRotateCameraVRDeviceOrientationInput;
  79765. }());
  79766. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79767. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79768. })(BABYLON || (BABYLON = {}));
  79769. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79770. var BABYLON;
  79771. (function (BABYLON) {
  79772. var VRCameraMetrics = /** @class */ (function () {
  79773. function VRCameraMetrics() {
  79774. this.compensateDistortion = true;
  79775. }
  79776. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79777. get: function () {
  79778. return this.hResolution / (2 * this.vResolution);
  79779. },
  79780. enumerable: true,
  79781. configurable: true
  79782. });
  79783. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79784. get: function () {
  79785. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79786. },
  79787. enumerable: true,
  79788. configurable: true
  79789. });
  79790. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79791. get: function () {
  79792. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79793. var h = (4 * meters) / this.hScreenSize;
  79794. return BABYLON.Matrix.Translation(h, 0, 0);
  79795. },
  79796. enumerable: true,
  79797. configurable: true
  79798. });
  79799. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79800. get: function () {
  79801. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79802. var h = (4 * meters) / this.hScreenSize;
  79803. return BABYLON.Matrix.Translation(-h, 0, 0);
  79804. },
  79805. enumerable: true,
  79806. configurable: true
  79807. });
  79808. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79809. get: function () {
  79810. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79811. },
  79812. enumerable: true,
  79813. configurable: true
  79814. });
  79815. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79816. get: function () {
  79817. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79818. },
  79819. enumerable: true,
  79820. configurable: true
  79821. });
  79822. VRCameraMetrics.GetDefault = function () {
  79823. var result = new VRCameraMetrics();
  79824. result.hResolution = 1280;
  79825. result.vResolution = 800;
  79826. result.hScreenSize = 0.149759993;
  79827. result.vScreenSize = 0.0935999975;
  79828. result.vScreenCenter = 0.0467999987;
  79829. result.eyeToScreenDistance = 0.0410000011;
  79830. result.lensSeparationDistance = 0.0635000020;
  79831. result.interpupillaryDistance = 0.0640000030;
  79832. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79833. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79834. result.postProcessScaleFactor = 1.714605507808412;
  79835. result.lensCenterOffset = 0.151976421;
  79836. return result;
  79837. };
  79838. return VRCameraMetrics;
  79839. }());
  79840. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79841. })(BABYLON || (BABYLON = {}));
  79842. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79843. var BABYLON;
  79844. (function (BABYLON) {
  79845. /**
  79846. * This represents a WebVR camera.
  79847. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79848. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79849. */
  79850. var WebVRFreeCamera = /** @class */ (function (_super) {
  79851. __extends(WebVRFreeCamera, _super);
  79852. /**
  79853. * Instantiates a WebVRFreeCamera.
  79854. * @param name The name of the WebVRFreeCamera
  79855. * @param position The starting anchor position for the camera
  79856. * @param scene The scene the camera belongs to
  79857. * @param webVROptions a set of customizable options for the webVRCamera
  79858. */
  79859. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79860. if (webVROptions === void 0) { webVROptions = {}; }
  79861. var _this = _super.call(this, name, position, scene) || this;
  79862. _this.webVROptions = webVROptions;
  79863. /**
  79864. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79865. */
  79866. _this._vrDevice = null;
  79867. /**
  79868. * The rawPose of the vrDevice.
  79869. */
  79870. _this.rawPose = null;
  79871. _this._specsVersion = "1.1";
  79872. _this._attached = false;
  79873. _this._descendants = [];
  79874. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79875. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79876. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79877. _this._standingMatrix = null;
  79878. /**
  79879. * Represents device position in babylon space.
  79880. */
  79881. _this.devicePosition = BABYLON.Vector3.Zero();
  79882. /**
  79883. * Represents device rotation in babylon space.
  79884. */
  79885. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79886. /**
  79887. * The scale of the device to be used when translating from device space to babylon space.
  79888. */
  79889. _this.deviceScaleFactor = 1;
  79890. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79891. _this._worldToDevice = BABYLON.Matrix.Identity();
  79892. /**
  79893. * References to the webVR controllers for the vrDevice.
  79894. */
  79895. _this.controllers = [];
  79896. /**
  79897. * Emits an event when a controller is attached.
  79898. */
  79899. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79900. /**
  79901. * Emits an event when a controller's mesh has been loaded;
  79902. */
  79903. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79904. /**
  79905. * If the rig cameras be used as parent instead of this camera.
  79906. */
  79907. _this.rigParenting = true;
  79908. _this._defaultHeight = undefined;
  79909. _this._workingVector = BABYLON.Vector3.Zero();
  79910. _this._oneVector = BABYLON.Vector3.One();
  79911. _this._workingMatrix = BABYLON.Matrix.Identity();
  79912. _this._cache.position = BABYLON.Vector3.Zero();
  79913. if (webVROptions.defaultHeight) {
  79914. _this._defaultHeight = webVROptions.defaultHeight;
  79915. _this.position.y = _this._defaultHeight;
  79916. }
  79917. _this.minZ = 0.1;
  79918. //legacy support - the compensation boolean was removed.
  79919. if (arguments.length === 5) {
  79920. _this.webVROptions = arguments[4];
  79921. }
  79922. // default webVR options
  79923. if (_this.webVROptions.trackPosition == undefined) {
  79924. _this.webVROptions.trackPosition = true;
  79925. }
  79926. if (_this.webVROptions.controllerMeshes == undefined) {
  79927. _this.webVROptions.controllerMeshes = true;
  79928. }
  79929. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79930. _this.webVROptions.defaultLightingOnControllers = true;
  79931. }
  79932. _this.rotationQuaternion = new BABYLON.Quaternion();
  79933. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79934. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79935. }
  79936. //enable VR
  79937. var engine = _this.getEngine();
  79938. _this._onVREnabled = function (success) { if (success) {
  79939. _this.initControllers();
  79940. } };
  79941. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79942. engine.initWebVR().add(function (event) {
  79943. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79944. return;
  79945. }
  79946. _this._vrDevice = event.vrDisplay;
  79947. //reset the rig parameters.
  79948. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79949. if (_this._attached) {
  79950. _this.getEngine().enableVR();
  79951. }
  79952. });
  79953. if (typeof (VRFrameData) !== "undefined")
  79954. _this._frameData = new VRFrameData();
  79955. /**
  79956. * The idea behind the following lines:
  79957. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79958. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79959. * the second will not show it correctly.
  79960. *
  79961. * To solve this - each object that has the camera as parent will be added to a protected array.
  79962. * When the rig camera renders, it will take this array and set all of those to be its children.
  79963. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79964. * Amazing!
  79965. */
  79966. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79967. if (camera.parent === _this && _this.rigParenting) {
  79968. _this._descendants = _this.getDescendants(true, function (n) {
  79969. // don't take the cameras or the controllers!
  79970. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79971. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79972. return !isController && !isRigCamera;
  79973. });
  79974. _this._descendants.forEach(function (node) {
  79975. node.parent = camera;
  79976. });
  79977. }
  79978. });
  79979. scene.onAfterCameraRenderObservable.add(function (camera) {
  79980. if (camera.parent === _this && _this.rigParenting) {
  79981. _this._descendants.forEach(function (node) {
  79982. node.parent = _this;
  79983. });
  79984. }
  79985. });
  79986. return _this;
  79987. }
  79988. /**
  79989. * Gets the device distance from the ground in meters.
  79990. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  79991. */
  79992. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79993. if (this._standingMatrix) {
  79994. // Add standing matrix offset to get real offset from ground in room
  79995. this._standingMatrix.getTranslationToRef(this._workingVector);
  79996. return this._deviceRoomPosition.y + this._workingVector.y;
  79997. }
  79998. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79999. return this._defaultHeight || 0;
  80000. };
  80001. /**
  80002. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80003. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80004. */
  80005. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80006. var _this = this;
  80007. if (callback === void 0) { callback = function (bool) { }; }
  80008. // Use standing matrix if available
  80009. this.getEngine().initWebVRAsync().then(function (result) {
  80010. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80011. callback(false);
  80012. }
  80013. else {
  80014. _this._standingMatrix = new BABYLON.Matrix();
  80015. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80016. if (!_this.getScene().useRightHandedSystem) {
  80017. [2, 6, 8, 9, 14].forEach(function (num) {
  80018. if (_this._standingMatrix) {
  80019. _this._standingMatrix.m[num] *= -1;
  80020. }
  80021. });
  80022. }
  80023. callback(true);
  80024. }
  80025. });
  80026. };
  80027. /**
  80028. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80029. * @returns A promise with a boolean set to if the standing matrix is supported.
  80030. */
  80031. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80032. var _this = this;
  80033. return new Promise(function (res, rej) {
  80034. _this.useStandingMatrix(function (supported) {
  80035. res(supported);
  80036. });
  80037. });
  80038. };
  80039. /**
  80040. * Disposes the camera
  80041. */
  80042. WebVRFreeCamera.prototype.dispose = function () {
  80043. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80044. _super.prototype.dispose.call(this);
  80045. };
  80046. /**
  80047. * Gets a vrController by name.
  80048. * @param name The name of the controller to retreive
  80049. * @returns the controller matching the name specified or null if not found
  80050. */
  80051. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80052. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80053. var gp = _a[_i];
  80054. if (gp.hand === name) {
  80055. return gp;
  80056. }
  80057. }
  80058. return null;
  80059. };
  80060. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80061. /**
  80062. * The controller corrisponding to the users left hand.
  80063. */
  80064. get: function () {
  80065. if (!this._leftController) {
  80066. this._leftController = this.getControllerByName("left");
  80067. }
  80068. return this._leftController;
  80069. },
  80070. enumerable: true,
  80071. configurable: true
  80072. });
  80073. ;
  80074. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80075. /**
  80076. * The controller corrisponding to the users right hand.
  80077. */
  80078. get: function () {
  80079. if (!this._rightController) {
  80080. this._rightController = this.getControllerByName("right");
  80081. }
  80082. return this._rightController;
  80083. },
  80084. enumerable: true,
  80085. configurable: true
  80086. });
  80087. ;
  80088. /**
  80089. * Casts a ray forward from the vrCamera's gaze.
  80090. * @param length Length of the ray (default: 100)
  80091. * @returns the ray corrisponding to the gaze
  80092. */
  80093. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80094. if (length === void 0) { length = 100; }
  80095. if (this.leftCamera) {
  80096. // Use left eye to avoid computation to compute center on every call
  80097. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80098. }
  80099. else {
  80100. return _super.prototype.getForwardRay.call(this, length);
  80101. }
  80102. };
  80103. /**
  80104. * Updates the camera based on device's frame data
  80105. */
  80106. WebVRFreeCamera.prototype._checkInputs = function () {
  80107. if (this._vrDevice && this._vrDevice.isPresenting) {
  80108. this._vrDevice.getFrameData(this._frameData);
  80109. this.updateFromDevice(this._frameData.pose);
  80110. }
  80111. _super.prototype._checkInputs.call(this);
  80112. };
  80113. /**
  80114. * Updates the poseControlled values based on the input device pose.
  80115. * @param poseData Pose coming from the device
  80116. */
  80117. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80118. if (poseData && poseData.orientation) {
  80119. this.rawPose = poseData;
  80120. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80121. if (this.getScene().useRightHandedSystem) {
  80122. this._deviceRoomRotationQuaternion.z *= -1;
  80123. this._deviceRoomRotationQuaternion.w *= -1;
  80124. }
  80125. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80126. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80127. if (this.getScene().useRightHandedSystem) {
  80128. this._deviceRoomPosition.z *= -1;
  80129. }
  80130. }
  80131. }
  80132. };
  80133. /**
  80134. * WebVR's attach control will start broadcasting frames to the device.
  80135. * Note that in certain browsers (chrome for example) this function must be called
  80136. * within a user-interaction callback. Example:
  80137. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80138. *
  80139. * @param element html element to attach the vrDevice to
  80140. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80141. */
  80142. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80143. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80144. this._attached = true;
  80145. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80146. if (this._vrDevice) {
  80147. this.getEngine().enableVR();
  80148. }
  80149. };
  80150. /**
  80151. * Detaches the camera from the html element and disables VR
  80152. *
  80153. * @param element html element to detach from
  80154. */
  80155. WebVRFreeCamera.prototype.detachControl = function (element) {
  80156. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80157. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80158. _super.prototype.detachControl.call(this, element);
  80159. this._attached = false;
  80160. this.getEngine().disableVR();
  80161. };
  80162. /**
  80163. * @returns the name of this class
  80164. */
  80165. WebVRFreeCamera.prototype.getClassName = function () {
  80166. return "WebVRFreeCamera";
  80167. };
  80168. /**
  80169. * Calls resetPose on the vrDisplay
  80170. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80171. */
  80172. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80173. //uses the vrDisplay's "resetPose()".
  80174. //pitch and roll won't be affected.
  80175. this._vrDevice.resetPose();
  80176. };
  80177. /**
  80178. * Updates the rig cameras (left and right eye)
  80179. */
  80180. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80181. var camLeft = this._rigCameras[0];
  80182. var camRight = this._rigCameras[1];
  80183. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80184. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80185. camLeft.position.copyFrom(this._deviceRoomPosition);
  80186. camRight.position.copyFrom(this._deviceRoomPosition);
  80187. };
  80188. /**
  80189. * Updates the cached values of the camera
  80190. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80191. */
  80192. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80193. var _this = this;
  80194. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80195. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80196. if (!this.updateCacheCalled) {
  80197. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80198. this.updateCacheCalled = true;
  80199. this.update();
  80200. }
  80201. // Set working vector to the device position in room space rotated by the new rotation
  80202. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80203. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80204. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80205. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80206. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80207. // Add translation from anchor position
  80208. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80209. this._workingVector.addInPlace(this.position);
  80210. this._workingVector.subtractInPlace(this._cache.position);
  80211. this._deviceToWorld.setTranslation(this._workingVector);
  80212. // Set an inverted matrix to be used when updating the camera
  80213. this._deviceToWorld.invertToRef(this._worldToDevice);
  80214. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80215. this.controllers.forEach(function (controller) {
  80216. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80217. controller.update();
  80218. });
  80219. }
  80220. if (!ignoreParentClass) {
  80221. _super.prototype._updateCache.call(this);
  80222. }
  80223. this.updateCacheCalled = false;
  80224. };
  80225. /**
  80226. * Updates the current device position and rotation in the babylon world
  80227. */
  80228. WebVRFreeCamera.prototype.update = function () {
  80229. // Get current device position in babylon world
  80230. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80231. // Get current device rotation in babylon world
  80232. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80233. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80234. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80235. _super.prototype.update.call(this);
  80236. };
  80237. /**
  80238. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80239. * @returns an identity matrix
  80240. */
  80241. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80242. return BABYLON.Matrix.Identity();
  80243. };
  80244. /**
  80245. * This function is called by the two RIG cameras.
  80246. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80247. */
  80248. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80249. var _this = this;
  80250. // Update the parent camera prior to using a child camera to avoid desynchronization
  80251. var parentCamera = this._cameraRigParams["parentCamera"];
  80252. parentCamera._updateCache();
  80253. //WebVR 1.1
  80254. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80255. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80256. if (!this.getScene().useRightHandedSystem) {
  80257. [2, 6, 8, 9, 14].forEach(function (num) {
  80258. _this._webvrViewMatrix.m[num] *= -1;
  80259. });
  80260. }
  80261. // update the camera rotation matrix
  80262. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80263. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80264. // Computing target and final matrix
  80265. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80266. // should the view matrix be updated with scale and position offset?
  80267. if (parentCamera.deviceScaleFactor !== 1) {
  80268. this._webvrViewMatrix.invert();
  80269. // scale the position, if set
  80270. if (parentCamera.deviceScaleFactor) {
  80271. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80272. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80273. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80274. }
  80275. this._webvrViewMatrix.invert();
  80276. }
  80277. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80278. return this._webvrViewMatrix;
  80279. };
  80280. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80281. var _this = this;
  80282. var parentCamera = this.parent;
  80283. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80284. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80285. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80286. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80287. //babylon compatible matrix
  80288. if (!this.getScene().useRightHandedSystem) {
  80289. [8, 9, 10, 11].forEach(function (num) {
  80290. _this._projectionMatrix.m[num] *= -1;
  80291. });
  80292. }
  80293. return this._projectionMatrix;
  80294. };
  80295. /**
  80296. * Initializes the controllers and their meshes
  80297. */
  80298. WebVRFreeCamera.prototype.initControllers = function () {
  80299. var _this = this;
  80300. this.controllers = [];
  80301. var manager = this.getScene().gamepadManager;
  80302. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80303. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80304. var webVrController = gamepad;
  80305. if (webVrController.defaultModel) {
  80306. webVrController.defaultModel.setEnabled(false);
  80307. }
  80308. if (webVrController.hand === "right") {
  80309. _this._rightController = null;
  80310. }
  80311. if (webVrController.hand === "left") {
  80312. _this._leftController = null;
  80313. }
  80314. var controllerIndex = _this.controllers.indexOf(webVrController);
  80315. if (controllerIndex !== -1) {
  80316. _this.controllers.splice(controllerIndex, 1);
  80317. }
  80318. }
  80319. });
  80320. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80321. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80322. var webVrController_1 = gamepad;
  80323. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80324. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80325. if (_this.webVROptions.controllerMeshes) {
  80326. if (webVrController_1.defaultModel) {
  80327. webVrController_1.defaultModel.setEnabled(true);
  80328. }
  80329. else {
  80330. // Load the meshes
  80331. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80332. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  80333. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80334. if (_this.webVROptions.defaultLightingOnControllers) {
  80335. if (!_this._lightOnControllers) {
  80336. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80337. }
  80338. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80339. var children = mesh.getChildren();
  80340. if (children.length !== 0) {
  80341. children.forEach(function (mesh) {
  80342. light.includedOnlyMeshes.push(mesh);
  80343. activateLightOnSubMeshes_1(mesh, light);
  80344. });
  80345. }
  80346. };
  80347. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80348. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80349. }
  80350. });
  80351. }
  80352. }
  80353. webVrController_1.attachToPoseControlledCamera(_this);
  80354. // since this is async - sanity check. Is the controller already stored?
  80355. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80356. //add to the controllers array
  80357. _this.controllers.push(webVrController_1);
  80358. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80359. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80360. // So we're overriding setting left & right manually to be sure
  80361. var firstViveWandDetected = false;
  80362. for (var i = 0; i < _this.controllers.length; i++) {
  80363. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80364. if (!firstViveWandDetected) {
  80365. firstViveWandDetected = true;
  80366. _this.controllers[i].hand = "left";
  80367. }
  80368. else {
  80369. _this.controllers[i].hand = "right";
  80370. }
  80371. }
  80372. }
  80373. //did we find enough controllers? Great! let the developer know.
  80374. if (_this.controllers.length >= 2) {
  80375. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80376. }
  80377. }
  80378. }
  80379. });
  80380. };
  80381. return WebVRFreeCamera;
  80382. }(BABYLON.FreeCamera));
  80383. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80384. })(BABYLON || (BABYLON = {}));
  80385. //# sourceMappingURL=babylon.webVRCamera.js.map
  80386. var BABYLON;
  80387. (function (BABYLON) {
  80388. // We're mainly based on the logic defined into the FreeCamera code
  80389. /**
  80390. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80391. * being tilted forward or back and left or right.
  80392. */
  80393. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80394. __extends(DeviceOrientationCamera, _super);
  80395. /**
  80396. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80397. * @param name The name of the camera
  80398. * @param position The start position camera
  80399. * @param scene The scene the camera belongs to
  80400. */
  80401. function DeviceOrientationCamera(name, position, scene) {
  80402. var _this = _super.call(this, name, position, scene) || this;
  80403. _this._quaternionCache = new BABYLON.Quaternion();
  80404. _this.inputs.addDeviceOrientation();
  80405. return _this;
  80406. }
  80407. /**
  80408. * Gets the current instance class name ("DeviceOrientationCamera").
  80409. * This helps avoiding instanceof at run time.
  80410. * @returns the class name
  80411. */
  80412. DeviceOrientationCamera.prototype.getClassName = function () {
  80413. return "DeviceOrientationCamera";
  80414. };
  80415. /**
  80416. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80417. */
  80418. DeviceOrientationCamera.prototype._checkInputs = function () {
  80419. _super.prototype._checkInputs.call(this);
  80420. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80421. if (this._initialQuaternion) {
  80422. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80423. }
  80424. };
  80425. /**
  80426. * Reset the camera to its default orientation on the specified axis only.
  80427. * @param axis The axis to reset
  80428. */
  80429. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80430. var _this = this;
  80431. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80432. //can only work if this camera has a rotation quaternion already.
  80433. if (!this.rotationQuaternion)
  80434. return;
  80435. if (!this._initialQuaternion) {
  80436. this._initialQuaternion = new BABYLON.Quaternion();
  80437. }
  80438. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80439. ['x', 'y', 'z'].forEach(function (axisName) {
  80440. if (!axis[axisName]) {
  80441. _this._initialQuaternion[axisName] = 0;
  80442. }
  80443. else {
  80444. _this._initialQuaternion[axisName] *= -1;
  80445. }
  80446. });
  80447. this._initialQuaternion.normalize();
  80448. //force rotation update
  80449. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80450. };
  80451. return DeviceOrientationCamera;
  80452. }(BABYLON.FreeCamera));
  80453. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80454. })(BABYLON || (BABYLON = {}));
  80455. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80456. var BABYLON;
  80457. (function (BABYLON) {
  80458. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80459. __extends(VRDeviceOrientationFreeCamera, _super);
  80460. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80461. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80462. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80463. var _this = _super.call(this, name, position, scene) || this;
  80464. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80465. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80466. return _this;
  80467. }
  80468. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80469. return "VRDeviceOrientationFreeCamera";
  80470. };
  80471. return VRDeviceOrientationFreeCamera;
  80472. }(BABYLON.DeviceOrientationCamera));
  80473. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80474. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80475. __extends(VRDeviceOrientationGamepadCamera, _super);
  80476. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80477. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80478. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80479. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80480. _this.inputs.addGamepad();
  80481. return _this;
  80482. }
  80483. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80484. return "VRDeviceOrientationGamepadCamera";
  80485. };
  80486. return VRDeviceOrientationGamepadCamera;
  80487. }(VRDeviceOrientationFreeCamera));
  80488. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80489. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80490. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80491. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80492. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80493. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80494. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80495. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80496. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80497. _this.inputs.addVRDeviceOrientation();
  80498. return _this;
  80499. }
  80500. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80501. return "VRDeviceOrientationArcRotateCamera";
  80502. };
  80503. return VRDeviceOrientationArcRotateCamera;
  80504. }(BABYLON.ArcRotateCamera));
  80505. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80506. })(BABYLON || (BABYLON = {}));
  80507. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80508. var BABYLON;
  80509. (function (BABYLON) {
  80510. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80511. __extends(AnaglyphFreeCamera, _super);
  80512. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80513. var _this = _super.call(this, name, position, scene) || this;
  80514. _this.interaxialDistance = interaxialDistance;
  80515. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80516. return _this;
  80517. }
  80518. AnaglyphFreeCamera.prototype.getClassName = function () {
  80519. return "AnaglyphFreeCamera";
  80520. };
  80521. return AnaglyphFreeCamera;
  80522. }(BABYLON.FreeCamera));
  80523. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80524. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80525. __extends(AnaglyphArcRotateCamera, _super);
  80526. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80527. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80528. _this.interaxialDistance = interaxialDistance;
  80529. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80530. return _this;
  80531. }
  80532. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80533. return "AnaglyphArcRotateCamera";
  80534. };
  80535. return AnaglyphArcRotateCamera;
  80536. }(BABYLON.ArcRotateCamera));
  80537. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80538. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80539. __extends(AnaglyphGamepadCamera, _super);
  80540. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80541. var _this = _super.call(this, name, position, scene) || this;
  80542. _this.interaxialDistance = interaxialDistance;
  80543. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80544. return _this;
  80545. }
  80546. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80547. return "AnaglyphGamepadCamera";
  80548. };
  80549. return AnaglyphGamepadCamera;
  80550. }(BABYLON.GamepadCamera));
  80551. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80552. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80553. __extends(AnaglyphUniversalCamera, _super);
  80554. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80555. var _this = _super.call(this, name, position, scene) || this;
  80556. _this.interaxialDistance = interaxialDistance;
  80557. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80558. return _this;
  80559. }
  80560. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80561. return "AnaglyphUniversalCamera";
  80562. };
  80563. return AnaglyphUniversalCamera;
  80564. }(BABYLON.UniversalCamera));
  80565. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80566. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80567. __extends(StereoscopicFreeCamera, _super);
  80568. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80569. var _this = _super.call(this, name, position, scene) || this;
  80570. _this.interaxialDistance = interaxialDistance;
  80571. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80572. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80573. return _this;
  80574. }
  80575. StereoscopicFreeCamera.prototype.getClassName = function () {
  80576. return "StereoscopicFreeCamera";
  80577. };
  80578. return StereoscopicFreeCamera;
  80579. }(BABYLON.FreeCamera));
  80580. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80581. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80582. __extends(StereoscopicArcRotateCamera, _super);
  80583. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80584. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80585. _this.interaxialDistance = interaxialDistance;
  80586. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80587. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80588. return _this;
  80589. }
  80590. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80591. return "StereoscopicArcRotateCamera";
  80592. };
  80593. return StereoscopicArcRotateCamera;
  80594. }(BABYLON.ArcRotateCamera));
  80595. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80596. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80597. __extends(StereoscopicGamepadCamera, _super);
  80598. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80599. var _this = _super.call(this, name, position, scene) || this;
  80600. _this.interaxialDistance = interaxialDistance;
  80601. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80602. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80603. return _this;
  80604. }
  80605. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80606. return "StereoscopicGamepadCamera";
  80607. };
  80608. return StereoscopicGamepadCamera;
  80609. }(BABYLON.GamepadCamera));
  80610. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80611. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80612. __extends(StereoscopicUniversalCamera, _super);
  80613. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80614. var _this = _super.call(this, name, position, scene) || this;
  80615. _this.interaxialDistance = interaxialDistance;
  80616. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80617. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80618. return _this;
  80619. }
  80620. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80621. return "StereoscopicUniversalCamera";
  80622. };
  80623. return StereoscopicUniversalCamera;
  80624. }(BABYLON.UniversalCamera));
  80625. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80626. })(BABYLON || (BABYLON = {}));
  80627. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80628. var BABYLON;
  80629. (function (BABYLON) {
  80630. var VRExperienceHelperGazer = /** @class */ (function () {
  80631. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80632. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80633. this.scene = scene;
  80634. this._pointerDownOnMeshAsked = false;
  80635. this._isActionableMesh = false;
  80636. this._teleportationRequestInitiated = false;
  80637. this._teleportationBackRequestInitiated = false;
  80638. this._dpadPressed = true;
  80639. this._activePointer = false;
  80640. this._id = VRExperienceHelperGazer._idCounter++;
  80641. // Gaze tracker
  80642. if (!gazeTrackerToClone) {
  80643. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80644. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80645. this._gazeTracker.isPickable = false;
  80646. this._gazeTracker.isVisible = false;
  80647. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80648. targetMat.specularColor = BABYLON.Color3.Black();
  80649. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80650. targetMat.backFaceCulling = false;
  80651. this._gazeTracker.material = targetMat;
  80652. }
  80653. else {
  80654. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80655. }
  80656. }
  80657. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80658. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80659. };
  80660. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80661. this._pointerDownOnMeshAsked = true;
  80662. if (this._currentMeshSelected && this._currentHit) {
  80663. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80664. }
  80665. };
  80666. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80667. if (this._currentMeshSelected && this._currentHit) {
  80668. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80669. }
  80670. this._pointerDownOnMeshAsked = false;
  80671. };
  80672. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80673. this._activePointer = true;
  80674. };
  80675. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80676. this._activePointer = false;
  80677. };
  80678. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80679. };
  80680. VRExperienceHelperGazer.prototype.dispose = function () {
  80681. this._interactionsEnabled = false;
  80682. this._teleportationEnabled = false;
  80683. };
  80684. VRExperienceHelperGazer._idCounter = 0;
  80685. return VRExperienceHelperGazer;
  80686. }());
  80687. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80688. __extends(VRExperienceHelperControllerGazer, _super);
  80689. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80690. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80691. _this.webVRController = webVRController;
  80692. // Laser pointer
  80693. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80694. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80695. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80696. laserPointerMaterial.alpha = 0.6;
  80697. _this._laserPointer.material = laserPointerMaterial;
  80698. _this._laserPointer.rotation.x = Math.PI / 2;
  80699. _this._laserPointer.position.z = -0.5;
  80700. _this._laserPointer.isVisible = false;
  80701. if (!webVRController.mesh) {
  80702. // Create an empty mesh that is used prior to loading the high quality model
  80703. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  80704. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  80705. preloadPointerPose.rotation.x = -0.7;
  80706. preloadMesh.addChild(preloadPointerPose);
  80707. webVRController.attachToMesh(preloadMesh);
  80708. }
  80709. _this._setLaserPointerParent(webVRController.mesh);
  80710. return _this;
  80711. }
  80712. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80713. return this.webVRController.getForwardRay(length);
  80714. };
  80715. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80716. _super.prototype._activatePointer.call(this);
  80717. this._laserPointer.isVisible = true;
  80718. };
  80719. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80720. _super.prototype._deactivatePointer.call(this);
  80721. this._laserPointer.isVisible = false;
  80722. };
  80723. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80724. this._laserPointer.material.emissiveColor = color;
  80725. };
  80726. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80727. var makeNotPick = function (root) {
  80728. root.name += " laserPointer";
  80729. root.getChildMeshes().forEach(function (c) {
  80730. makeNotPick(c);
  80731. });
  80732. };
  80733. makeNotPick(mesh);
  80734. var childMeshes = mesh.getChildMeshes();
  80735. this.webVRController._pointingPoseNode = null;
  80736. for (var i = 0; i < childMeshes.length; i++) {
  80737. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  80738. mesh = childMeshes[i];
  80739. this.webVRController._pointingPoseNode = mesh;
  80740. break;
  80741. }
  80742. }
  80743. this._laserPointer.parent = mesh;
  80744. };
  80745. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80746. this._laserPointer.scaling.y = distance;
  80747. this._laserPointer.position.z = -distance / 2;
  80748. };
  80749. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80750. _super.prototype.dispose.call(this);
  80751. this._laserPointer.dispose();
  80752. };
  80753. return VRExperienceHelperControllerGazer;
  80754. }(VRExperienceHelperGazer));
  80755. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80756. __extends(VRExperienceHelperCameraGazer, _super);
  80757. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80758. var _this = _super.call(this, scene) || this;
  80759. _this.getCamera = getCamera;
  80760. return _this;
  80761. }
  80762. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80763. var camera = this.getCamera();
  80764. if (camera) {
  80765. return camera.getForwardRay(length);
  80766. }
  80767. else {
  80768. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80769. }
  80770. };
  80771. return VRExperienceHelperCameraGazer;
  80772. }(VRExperienceHelperGazer));
  80773. /**
  80774. * Helps to quickly add VR support to an existing scene.
  80775. * See http://doc.babylonjs.com/how_to/webvr_helper
  80776. */
  80777. var VRExperienceHelper = /** @class */ (function () {
  80778. /**
  80779. * Instantiates a VRExperienceHelper.
  80780. * Helps to quickly add VR support to an existing scene.
  80781. * @param scene The scene the VRExperienceHelper belongs to.
  80782. * @param webVROptions Options to modify the vr experience helper's behavior.
  80783. */
  80784. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80785. if (webVROptions === void 0) { webVROptions = {}; }
  80786. var _this = this;
  80787. this.webVROptions = webVROptions;
  80788. // Can the system support WebVR, even if a headset isn't plugged in?
  80789. this._webVRsupported = false;
  80790. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80791. this._webVRready = false;
  80792. // Are we waiting for the requestPresent callback to complete?
  80793. this._webVRrequesting = false;
  80794. // Are we presenting to the headset right now?
  80795. this._webVRpresenting = false;
  80796. // Are we presenting in the fullscreen fallback?
  80797. this._fullscreenVRpresenting = false;
  80798. /**
  80799. * Observable raised when entering VR.
  80800. */
  80801. this.onEnteringVRObservable = new BABYLON.Observable();
  80802. /**
  80803. * Observable raised when exiting VR.
  80804. */
  80805. this.onExitingVRObservable = new BABYLON.Observable();
  80806. /**
  80807. * Observable raised when controller mesh is loaded.
  80808. */
  80809. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80810. this._useCustomVRButton = false;
  80811. this._teleportationRequested = false;
  80812. this._teleportActive = false;
  80813. this._floorMeshesCollection = [];
  80814. this._rotationAllowed = true;
  80815. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80816. this._rotationRightAsked = false;
  80817. this._rotationLeftAsked = false;
  80818. this._isDefaultTeleportationTarget = true;
  80819. this._teleportationFillColor = "#444444";
  80820. this._teleportationBorderColor = "#FFFFFF";
  80821. this._rotationAngle = 0;
  80822. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80823. this._padSensibilityUp = 0.65;
  80824. this._padSensibilityDown = 0.35;
  80825. this.leftController = null;
  80826. this.rightController = null;
  80827. /**
  80828. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80829. */
  80830. this.onNewMeshSelected = new BABYLON.Observable();
  80831. /**
  80832. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80833. */
  80834. this.onNewMeshPicked = new BABYLON.Observable();
  80835. /**
  80836. * Observable raised before camera teleportation
  80837. */
  80838. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80839. /**
  80840. * Observable raised after camera teleportation
  80841. */
  80842. this.onAfterCameraTeleport = new BABYLON.Observable();
  80843. /**
  80844. * Observable raised when current selected mesh gets unselected
  80845. */
  80846. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80847. /**
  80848. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80849. */
  80850. this.teleportationEnabled = true;
  80851. this._teleportationInitialized = false;
  80852. this._interactionsEnabled = false;
  80853. this._interactionsRequested = false;
  80854. this._displayGaze = true;
  80855. this._displayLaserPointer = true;
  80856. this._onResize = function () {
  80857. _this.moveButtonToBottomRight();
  80858. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80859. _this.exitVR();
  80860. }
  80861. };
  80862. this._onFullscreenChange = function () {
  80863. if (document.fullscreen !== undefined) {
  80864. _this._fullscreenVRpresenting = document.fullscreen;
  80865. }
  80866. else if (document.mozFullScreen !== undefined) {
  80867. _this._fullscreenVRpresenting = document.mozFullScreen;
  80868. }
  80869. else if (document.webkitIsFullScreen !== undefined) {
  80870. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80871. }
  80872. else if (document.msIsFullScreen !== undefined) {
  80873. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80874. }
  80875. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80876. _this.exitVR();
  80877. if (!_this._useCustomVRButton) {
  80878. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80879. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80880. }
  80881. }
  80882. };
  80883. this.beforeRender = function () {
  80884. if (_this.leftController && _this.leftController._activePointer) {
  80885. _this._castRayAndSelectObject(_this.leftController);
  80886. }
  80887. if (_this.rightController && _this.rightController._activePointer) {
  80888. _this._castRayAndSelectObject(_this.rightController);
  80889. }
  80890. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80891. _this._castRayAndSelectObject(_this._cameraGazer);
  80892. }
  80893. else {
  80894. _this._cameraGazer._gazeTracker.isVisible = false;
  80895. }
  80896. };
  80897. this._onNewGamepadConnected = function (gamepad) {
  80898. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80899. if (gamepad.leftStick) {
  80900. gamepad.onleftstickchanged(function (stickValues) {
  80901. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80902. // Listening to classic/xbox gamepad only if no VR controller is active
  80903. if ((!_this.leftController && !_this.rightController) ||
  80904. ((_this.leftController && !_this.leftController._activePointer) &&
  80905. (_this.rightController && !_this.rightController._activePointer))) {
  80906. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80907. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80908. }
  80909. }
  80910. });
  80911. }
  80912. if (gamepad.rightStick) {
  80913. gamepad.onrightstickchanged(function (stickValues) {
  80914. if (_this._teleportationInitialized) {
  80915. _this._checkRotate(stickValues, _this._cameraGazer);
  80916. }
  80917. });
  80918. }
  80919. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80920. gamepad.onbuttondown(function (buttonPressed) {
  80921. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80922. _this._cameraGazer._selectionPointerDown();
  80923. }
  80924. });
  80925. gamepad.onbuttonup(function (buttonPressed) {
  80926. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80927. _this._cameraGazer._selectionPointerUp();
  80928. }
  80929. });
  80930. }
  80931. }
  80932. else {
  80933. var webVRController = gamepad;
  80934. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80935. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80936. _this.rightController = controller;
  80937. }
  80938. else {
  80939. _this.leftController = controller;
  80940. }
  80941. _this._tryEnableInteractionOnController(controller);
  80942. }
  80943. };
  80944. // 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
  80945. this._tryEnableInteractionOnController = function (controller) {
  80946. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80947. _this._enableInteractionOnController(controller);
  80948. }
  80949. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80950. _this._enableTeleportationOnController(controller);
  80951. }
  80952. };
  80953. this._onNewGamepadDisconnected = function (gamepad) {
  80954. if (gamepad instanceof BABYLON.WebVRController) {
  80955. if (gamepad.hand === "left" && _this.leftController != null) {
  80956. _this.leftController.dispose();
  80957. _this.leftController = null;
  80958. }
  80959. if (gamepad.hand === "right" && _this.rightController != null) {
  80960. _this.rightController.dispose();
  80961. _this.rightController = null;
  80962. }
  80963. }
  80964. };
  80965. this._workingVector = BABYLON.Vector3.Zero();
  80966. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80967. this._workingMatrix = BABYLON.Matrix.Identity();
  80968. this._scene = scene;
  80969. this._canvas = scene.getEngine().getRenderingCanvas();
  80970. // Parse options
  80971. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80972. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80973. }
  80974. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80975. webVROptions.createDeviceOrientationCamera = true;
  80976. }
  80977. if (webVROptions.defaultHeight === undefined) {
  80978. webVROptions.defaultHeight = 1.7;
  80979. }
  80980. if (webVROptions.useCustomVRButton) {
  80981. this._useCustomVRButton = true;
  80982. if (webVROptions.customVRButton) {
  80983. this._btnVR = webVROptions.customVRButton;
  80984. }
  80985. }
  80986. if (webVROptions.rayLength) {
  80987. this._rayLength = webVROptions.rayLength;
  80988. }
  80989. this._defaultHeight = webVROptions.defaultHeight;
  80990. if (webVROptions.positionScale) {
  80991. this._rayLength *= webVROptions.positionScale;
  80992. this._defaultHeight *= webVROptions.positionScale;
  80993. }
  80994. // Set position
  80995. if (this._scene.activeCamera) {
  80996. this._position = this._scene.activeCamera.position.clone();
  80997. }
  80998. else {
  80999. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81000. }
  81001. // Set non-vr camera
  81002. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81003. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81004. // Copy data from existing camera
  81005. if (this._scene.activeCamera) {
  81006. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81007. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81008. // Set rotation from previous camera
  81009. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81010. var targetCamera = this._scene.activeCamera;
  81011. if (targetCamera.rotationQuaternion) {
  81012. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81013. }
  81014. else {
  81015. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81016. }
  81017. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81018. }
  81019. }
  81020. this._scene.activeCamera = this._deviceOrientationCamera;
  81021. if (this._canvas) {
  81022. this._scene.activeCamera.attachControl(this._canvas);
  81023. }
  81024. }
  81025. else {
  81026. this._existingCamera = this._scene.activeCamera;
  81027. }
  81028. // Create VR cameras
  81029. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81030. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81031. }
  81032. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81033. this._webVRCamera.useStandingMatrix();
  81034. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81035. // Create default button
  81036. if (!this._useCustomVRButton) {
  81037. this._btnVR = document.createElement("BUTTON");
  81038. this._btnVR.className = "babylonVRicon";
  81039. this._btnVR.id = "babylonVRiconbtn";
  81040. this._btnVR.title = "Click to switch to VR";
  81041. 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) }";
  81042. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81043. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81044. // css += ".babylonVRicon.vrdisplaysupported { }";
  81045. // css += ".babylonVRicon.vrdisplayready { }";
  81046. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81047. var style = document.createElement('style');
  81048. style.appendChild(document.createTextNode(css));
  81049. document.getElementsByTagName('head')[0].appendChild(style);
  81050. this.moveButtonToBottomRight();
  81051. }
  81052. // VR button click event
  81053. if (this._btnVR) {
  81054. this._btnVR.addEventListener("click", function () {
  81055. if (!_this.isInVRMode) {
  81056. _this.enterVR();
  81057. }
  81058. else {
  81059. _this.exitVR();
  81060. }
  81061. });
  81062. }
  81063. // Window events
  81064. window.addEventListener("resize", this._onResize);
  81065. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81066. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81067. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81068. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81069. // Display vr button when headset is connected
  81070. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81071. this.displayVRButton();
  81072. }
  81073. else {
  81074. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81075. if (e.vrDisplay) {
  81076. _this.displayVRButton();
  81077. }
  81078. });
  81079. }
  81080. // Exiting VR mode using 'ESC' key on desktop
  81081. this._onKeyDown = function (event) {
  81082. if (event.keyCode === 27 && _this.isInVRMode) {
  81083. _this.exitVR();
  81084. }
  81085. };
  81086. document.addEventListener("keydown", this._onKeyDown);
  81087. // Exiting VR mode double tapping the touch screen
  81088. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81089. if (_this.isInVRMode) {
  81090. _this.exitVR();
  81091. if (_this._fullscreenVRpresenting) {
  81092. _this._scene.getEngine().switchFullscreen(true);
  81093. }
  81094. }
  81095. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81096. // Listen for WebVR display changes
  81097. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81098. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81099. this._onVRRequestPresentStart = function () {
  81100. _this._webVRrequesting = true;
  81101. _this.updateButtonVisibility();
  81102. };
  81103. this._onVRRequestPresentComplete = function (success) {
  81104. _this._webVRrequesting = false;
  81105. _this.updateButtonVisibility();
  81106. };
  81107. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81108. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81109. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81110. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81111. scene.onDisposeObservable.add(function () {
  81112. _this.dispose();
  81113. });
  81114. // Gamepad connection events
  81115. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81116. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81117. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81118. this.updateButtonVisibility();
  81119. //create easing functions
  81120. this._circleEase = new BABYLON.CircleEase();
  81121. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81122. }
  81123. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81124. /** Return this.onEnteringVRObservable
  81125. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81126. */
  81127. get: function () {
  81128. return this.onEnteringVRObservable;
  81129. },
  81130. enumerable: true,
  81131. configurable: true
  81132. });
  81133. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81134. /** Return this.onExitingVRObservable
  81135. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81136. */
  81137. get: function () {
  81138. return this.onExitingVRObservable;
  81139. },
  81140. enumerable: true,
  81141. configurable: true
  81142. });
  81143. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81144. /** Return this.onControllerMeshLoadedObservable
  81145. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81146. */
  81147. get: function () {
  81148. return this.onControllerMeshLoadedObservable;
  81149. },
  81150. enumerable: true,
  81151. configurable: true
  81152. });
  81153. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81154. /**
  81155. * The mesh used to display where the user is going to teleport.
  81156. */
  81157. get: function () {
  81158. return this._teleportationTarget;
  81159. },
  81160. /**
  81161. * Sets the mesh to be used to display where the user is going to teleport.
  81162. */
  81163. set: function (value) {
  81164. if (value) {
  81165. value.name = "teleportationTarget";
  81166. this._isDefaultTeleportationTarget = false;
  81167. this._teleportationTarget = value;
  81168. }
  81169. },
  81170. enumerable: true,
  81171. configurable: true
  81172. });
  81173. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81174. /**
  81175. * The mesh used to display where the user is selecting,
  81176. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81177. * See http://doc.babylonjs.com/resources/baking_transformations
  81178. */
  81179. get: function () {
  81180. return this._cameraGazer._gazeTracker;
  81181. },
  81182. set: function (value) {
  81183. if (value) {
  81184. this._cameraGazer._gazeTracker = value;
  81185. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81186. this._cameraGazer._gazeTracker.isPickable = false;
  81187. this._cameraGazer._gazeTracker.isVisible = false;
  81188. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81189. if (this.leftController) {
  81190. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81191. }
  81192. if (this.rightController) {
  81193. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81194. }
  81195. }
  81196. },
  81197. enumerable: true,
  81198. configurable: true
  81199. });
  81200. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81201. /**
  81202. * If the ray of the gaze should be displayed.
  81203. */
  81204. get: function () {
  81205. return this._displayGaze;
  81206. },
  81207. /**
  81208. * Sets if the ray of the gaze should be displayed.
  81209. */
  81210. set: function (value) {
  81211. this._displayGaze = value;
  81212. if (!value) {
  81213. this._cameraGazer._gazeTracker.isVisible = false;
  81214. if (this.leftController) {
  81215. this.leftController._gazeTracker.isVisible = false;
  81216. }
  81217. if (this.rightController) {
  81218. this.rightController._gazeTracker.isVisible = false;
  81219. }
  81220. }
  81221. },
  81222. enumerable: true,
  81223. configurable: true
  81224. });
  81225. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81226. /**
  81227. * If the ray of the LaserPointer should be displayed.
  81228. */
  81229. get: function () {
  81230. return this._displayLaserPointer;
  81231. },
  81232. /**
  81233. * Sets if the ray of the LaserPointer should be displayed.
  81234. */
  81235. set: function (value) {
  81236. this._displayLaserPointer = value;
  81237. if (!value) {
  81238. if (this.rightController) {
  81239. this.rightController._deactivatePointer();
  81240. this.rightController._gazeTracker.isVisible = false;
  81241. }
  81242. if (this.leftController) {
  81243. this.leftController._deactivatePointer();
  81244. this.leftController._gazeTracker.isVisible = false;
  81245. }
  81246. }
  81247. else {
  81248. if (this.rightController) {
  81249. this.rightController._activatePointer();
  81250. }
  81251. else if (this.leftController) {
  81252. this.leftController._activatePointer();
  81253. }
  81254. }
  81255. },
  81256. enumerable: true,
  81257. configurable: true
  81258. });
  81259. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81260. /**
  81261. * The deviceOrientationCamera used as the camera when not in VR.
  81262. */
  81263. get: function () {
  81264. return this._deviceOrientationCamera;
  81265. },
  81266. enumerable: true,
  81267. configurable: true
  81268. });
  81269. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81270. /**
  81271. * Based on the current WebVR support, returns the current VR camera used.
  81272. */
  81273. get: function () {
  81274. if (this._webVRready) {
  81275. return this._webVRCamera;
  81276. }
  81277. else {
  81278. return this._scene.activeCamera;
  81279. }
  81280. },
  81281. enumerable: true,
  81282. configurable: true
  81283. });
  81284. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81285. /**
  81286. * The webVRCamera which is used when in VR.
  81287. */
  81288. get: function () {
  81289. return this._webVRCamera;
  81290. },
  81291. enumerable: true,
  81292. configurable: true
  81293. });
  81294. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81295. /**
  81296. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81297. */
  81298. get: function () {
  81299. return this._vrDeviceOrientationCamera;
  81300. },
  81301. enumerable: true,
  81302. configurable: true
  81303. });
  81304. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81305. get: function () {
  81306. var result = this._cameraGazer._teleportationRequestInitiated
  81307. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81308. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81309. return result;
  81310. },
  81311. enumerable: true,
  81312. configurable: true
  81313. });
  81314. // Raised when one of the controller has loaded successfully its associated default mesh
  81315. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81316. if (this.leftController && this.leftController.webVRController == webVRController) {
  81317. if (webVRController.mesh) {
  81318. this.leftController._setLaserPointerParent(webVRController.mesh);
  81319. }
  81320. }
  81321. if (this.rightController && this.rightController.webVRController == webVRController) {
  81322. if (webVRController.mesh) {
  81323. this.rightController._setLaserPointerParent(webVRController.mesh);
  81324. }
  81325. }
  81326. try {
  81327. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81328. }
  81329. catch (err) {
  81330. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81331. }
  81332. };
  81333. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81334. /**
  81335. * Gets a value indicating if we are currently in VR mode.
  81336. */
  81337. get: function () {
  81338. return this._webVRpresenting || this._fullscreenVRpresenting;
  81339. },
  81340. enumerable: true,
  81341. configurable: true
  81342. });
  81343. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81344. var vrDisplay = this._scene.getEngine().getVRDevice();
  81345. if (vrDisplay) {
  81346. var wasPresenting = this._webVRpresenting;
  81347. // A VR display is connected
  81348. this._webVRpresenting = vrDisplay.isPresenting;
  81349. if (wasPresenting && !this._webVRpresenting)
  81350. this.exitVR();
  81351. }
  81352. else {
  81353. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81354. }
  81355. this.updateButtonVisibility();
  81356. };
  81357. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81358. this._webVRsupported = eventArgs.vrSupported;
  81359. this._webVRready = !!eventArgs.vrDisplay;
  81360. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81361. this.updateButtonVisibility();
  81362. };
  81363. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81364. if (this._canvas && !this._useCustomVRButton) {
  81365. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81366. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81367. }
  81368. };
  81369. VRExperienceHelper.prototype.displayVRButton = function () {
  81370. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81371. document.body.appendChild(this._btnVR);
  81372. this._btnVRDisplayed = true;
  81373. }
  81374. };
  81375. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81376. if (!this._btnVR || this._useCustomVRButton) {
  81377. return;
  81378. }
  81379. this._btnVR.className = "babylonVRicon";
  81380. if (this.isInVRMode) {
  81381. this._btnVR.className += " vrdisplaypresenting";
  81382. }
  81383. else {
  81384. if (this._webVRready)
  81385. this._btnVR.className += " vrdisplayready";
  81386. if (this._webVRsupported)
  81387. this._btnVR.className += " vrdisplaysupported";
  81388. if (this._webVRrequesting)
  81389. this._btnVR.className += " vrdisplayrequesting";
  81390. }
  81391. };
  81392. /**
  81393. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81394. * Otherwise, will use the fullscreen API.
  81395. */
  81396. VRExperienceHelper.prototype.enterVR = function () {
  81397. if (this.onEnteringVRObservable) {
  81398. try {
  81399. this.onEnteringVRObservable.notifyObservers(this);
  81400. }
  81401. catch (err) {
  81402. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81403. }
  81404. }
  81405. if (this._scene.activeCamera) {
  81406. this._position = this._scene.activeCamera.position.clone();
  81407. // make sure that we return to the last active camera
  81408. this._existingCamera = this._scene.activeCamera;
  81409. }
  81410. if (this._webVRrequesting)
  81411. return;
  81412. // If WebVR is supported and a headset is connected
  81413. if (this._webVRready) {
  81414. if (!this._webVRpresenting) {
  81415. this._webVRCamera.position = this._position;
  81416. this._scene.activeCamera = this._webVRCamera;
  81417. }
  81418. }
  81419. else if (this._vrDeviceOrientationCamera) {
  81420. this._vrDeviceOrientationCamera.position = this._position;
  81421. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81422. this._scene.getEngine().switchFullscreen(true);
  81423. this.updateButtonVisibility();
  81424. }
  81425. if (this._scene.activeCamera && this._canvas) {
  81426. this._scene.activeCamera.attachControl(this._canvas);
  81427. }
  81428. if (this._interactionsEnabled) {
  81429. this._scene.registerBeforeRender(this.beforeRender);
  81430. }
  81431. };
  81432. /**
  81433. * Attempt to exit VR, or fullscreen.
  81434. */
  81435. VRExperienceHelper.prototype.exitVR = function () {
  81436. if (this.onExitingVRObservable) {
  81437. try {
  81438. this.onExitingVRObservable.notifyObservers(this);
  81439. }
  81440. catch (err) {
  81441. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81442. }
  81443. }
  81444. if (this._webVRpresenting) {
  81445. this._scene.getEngine().disableVR();
  81446. }
  81447. if (this._scene.activeCamera) {
  81448. this._position = this._scene.activeCamera.position.clone();
  81449. }
  81450. if (this._deviceOrientationCamera) {
  81451. this._deviceOrientationCamera.position = this._position;
  81452. this._scene.activeCamera = this._deviceOrientationCamera;
  81453. if (this._canvas) {
  81454. this._scene.activeCamera.attachControl(this._canvas);
  81455. }
  81456. }
  81457. else if (this._existingCamera) {
  81458. this._existingCamera.position = this._position;
  81459. this._scene.activeCamera = this._existingCamera;
  81460. }
  81461. this.updateButtonVisibility();
  81462. if (this._interactionsEnabled) {
  81463. this._scene.unregisterBeforeRender(this.beforeRender);
  81464. }
  81465. };
  81466. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81467. /**
  81468. * The position of the vr experience helper.
  81469. */
  81470. get: function () {
  81471. return this._position;
  81472. },
  81473. /**
  81474. * Sets the position of the vr experience helper.
  81475. */
  81476. set: function (value) {
  81477. this._position = value;
  81478. if (this._scene.activeCamera) {
  81479. this._scene.activeCamera.position = value;
  81480. }
  81481. },
  81482. enumerable: true,
  81483. configurable: true
  81484. });
  81485. /**
  81486. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81487. */
  81488. VRExperienceHelper.prototype.enableInteractions = function () {
  81489. var _this = this;
  81490. if (!this._interactionsEnabled) {
  81491. this._interactionsRequested = true;
  81492. if (this.leftController) {
  81493. this._enableInteractionOnController(this.leftController);
  81494. }
  81495. if (this.rightController) {
  81496. this._enableInteractionOnController(this.rightController);
  81497. }
  81498. this.raySelectionPredicate = function (mesh) {
  81499. return mesh.isVisible;
  81500. };
  81501. this.meshSelectionPredicate = function (mesh) {
  81502. return true;
  81503. };
  81504. this._raySelectionPredicate = function (mesh) {
  81505. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81506. && mesh.name.indexOf("teleportationTarget") === -1
  81507. && mesh.name.indexOf("torusTeleportation") === -1
  81508. && mesh.name.indexOf("laserPointer") === -1)) {
  81509. return _this.raySelectionPredicate(mesh);
  81510. }
  81511. return false;
  81512. };
  81513. this._interactionsEnabled = true;
  81514. }
  81515. };
  81516. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81517. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81518. if (this._floorMeshesCollection[i].id === mesh.id) {
  81519. return true;
  81520. }
  81521. }
  81522. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81523. return true;
  81524. }
  81525. return false;
  81526. };
  81527. /**
  81528. * Adds a floor mesh to be used for teleportation.
  81529. * @param floorMesh the mesh to be used for teleportation.
  81530. */
  81531. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81532. if (!this._floorMeshesCollection) {
  81533. return;
  81534. }
  81535. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81536. return;
  81537. }
  81538. this._floorMeshesCollection.push(floorMesh);
  81539. };
  81540. /**
  81541. * Removes a floor mesh from being used for teleportation.
  81542. * @param floorMesh the mesh to be removed.
  81543. */
  81544. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81545. if (!this._floorMeshesCollection) {
  81546. return;
  81547. }
  81548. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81549. if (meshIndex !== -1) {
  81550. this._floorMeshesCollection.splice(meshIndex, 1);
  81551. }
  81552. };
  81553. /**
  81554. * Enables interactions and teleportation using the VR controllers and gaze.
  81555. * @param vrTeleportationOptions options to modify teleportation behavior.
  81556. */
  81557. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81558. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81559. if (!this._teleportationInitialized) {
  81560. this._teleportationRequested = true;
  81561. this.enableInteractions();
  81562. if (vrTeleportationOptions.floorMeshName) {
  81563. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81564. }
  81565. if (vrTeleportationOptions.floorMeshes) {
  81566. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81567. }
  81568. if (this.leftController != null) {
  81569. this._enableTeleportationOnController(this.leftController);
  81570. }
  81571. if (this.rightController != null) {
  81572. this._enableTeleportationOnController(this.rightController);
  81573. }
  81574. // Creates an image processing post process for the vignette not relying
  81575. // on the main scene configuration for image processing to reduce setup and spaces
  81576. // (gamma/linear) conflicts.
  81577. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81578. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81579. imageProcessingConfiguration.vignetteEnabled = true;
  81580. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81581. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81582. this._teleportationInitialized = true;
  81583. if (this._isDefaultTeleportationTarget) {
  81584. this._createTeleportationCircles();
  81585. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81586. }
  81587. }
  81588. };
  81589. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81590. var _this = this;
  81591. var controllerMesh = controller.webVRController.mesh;
  81592. if (controllerMesh) {
  81593. controller._interactionsEnabled = true;
  81594. controller._activatePointer();
  81595. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81596. // Enabling / disabling laserPointer
  81597. if (_this._displayLaserPointer && stateObject.value === 1) {
  81598. if (controller._activePointer) {
  81599. controller._deactivatePointer();
  81600. }
  81601. else {
  81602. controller._activatePointer();
  81603. }
  81604. if (_this.displayGaze) {
  81605. controller._gazeTracker.isVisible = controller._activePointer;
  81606. }
  81607. }
  81608. });
  81609. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81610. if (!controller._pointerDownOnMeshAsked) {
  81611. if (stateObject.value > _this._padSensibilityUp) {
  81612. controller._selectionPointerDown();
  81613. }
  81614. }
  81615. else if (stateObject.value < _this._padSensibilityDown) {
  81616. controller._selectionPointerUp();
  81617. }
  81618. });
  81619. }
  81620. };
  81621. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81622. // Dont teleport if another gaze already requested teleportation
  81623. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81624. return;
  81625. }
  81626. if (!gazer._teleportationRequestInitiated) {
  81627. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81628. gazer._activatePointer();
  81629. gazer._teleportationRequestInitiated = true;
  81630. }
  81631. }
  81632. else {
  81633. // Listening to the proper controller values changes to confirm teleportation
  81634. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81635. if (this._teleportActive) {
  81636. this._teleportCamera(this._haloCenter);
  81637. }
  81638. gazer._teleportationRequestInitiated = false;
  81639. }
  81640. }
  81641. };
  81642. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81643. // Only rotate when user is not currently selecting a teleportation location
  81644. if (gazer._teleportationRequestInitiated) {
  81645. return;
  81646. }
  81647. if (!this._rotationLeftAsked) {
  81648. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81649. this._rotationLeftAsked = true;
  81650. if (this._rotationAllowed) {
  81651. this._rotateCamera(false);
  81652. }
  81653. }
  81654. }
  81655. else {
  81656. if (stateObject.x > -this._padSensibilityDown) {
  81657. this._rotationLeftAsked = false;
  81658. }
  81659. }
  81660. if (!this._rotationRightAsked) {
  81661. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81662. this._rotationRightAsked = true;
  81663. if (this._rotationAllowed) {
  81664. this._rotateCamera(true);
  81665. }
  81666. }
  81667. }
  81668. else {
  81669. if (stateObject.x < this._padSensibilityDown) {
  81670. this._rotationRightAsked = false;
  81671. }
  81672. }
  81673. };
  81674. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81675. // Only teleport backwards when user is not currently selecting a teleportation location
  81676. if (gazer._teleportationRequestInitiated) {
  81677. return;
  81678. }
  81679. // Teleport backwards
  81680. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81681. if (!gazer._teleportationBackRequestInitiated) {
  81682. if (!this.currentVRCamera) {
  81683. return;
  81684. }
  81685. // Get rotation and position of the current camera
  81686. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81687. var position = this.currentVRCamera.position;
  81688. // If the camera has device position, use that instead
  81689. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81690. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81691. position = this.currentVRCamera.devicePosition;
  81692. }
  81693. // Get matrix with only the y rotation of the device rotation
  81694. rotation.toEulerAnglesToRef(this._workingVector);
  81695. this._workingVector.z = 0;
  81696. this._workingVector.x = 0;
  81697. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81698. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81699. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81700. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81701. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81702. var ray = new BABYLON.Ray(position, this._workingVector);
  81703. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81704. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81705. this._teleportCamera(hit.pickedPoint);
  81706. }
  81707. gazer._teleportationBackRequestInitiated = true;
  81708. }
  81709. }
  81710. else {
  81711. gazer._teleportationBackRequestInitiated = false;
  81712. }
  81713. };
  81714. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81715. var _this = this;
  81716. var controllerMesh = controller.webVRController.mesh;
  81717. if (controllerMesh) {
  81718. if (!controller._interactionsEnabled) {
  81719. this._enableInteractionOnController(controller);
  81720. }
  81721. controller._interactionsEnabled = true;
  81722. controller._teleportationEnabled = true;
  81723. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81724. controller._dpadPressed = false;
  81725. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81726. controller._dpadPressed = stateObject.pressed;
  81727. if (!controller._dpadPressed) {
  81728. _this._rotationLeftAsked = false;
  81729. _this._rotationRightAsked = false;
  81730. controller._teleportationBackRequestInitiated = false;
  81731. }
  81732. });
  81733. }
  81734. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81735. if (_this.teleportationEnabled) {
  81736. _this._checkTeleportBackwards(stateObject, controller);
  81737. _this._checkTeleportWithRay(stateObject, controller);
  81738. }
  81739. _this._checkRotate(stateObject, controller);
  81740. });
  81741. }
  81742. };
  81743. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81744. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81745. this._teleportationTarget.isPickable = false;
  81746. var length = 512;
  81747. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81748. dynamicTexture.hasAlpha = true;
  81749. var context = dynamicTexture.getContext();
  81750. var centerX = length / 2;
  81751. var centerY = length / 2;
  81752. var radius = 200;
  81753. context.beginPath();
  81754. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81755. context.fillStyle = this._teleportationFillColor;
  81756. context.fill();
  81757. context.lineWidth = 10;
  81758. context.strokeStyle = this._teleportationBorderColor;
  81759. context.stroke();
  81760. context.closePath();
  81761. dynamicTexture.update();
  81762. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81763. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81764. this._teleportationTarget.material = teleportationCircleMaterial;
  81765. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81766. torus.isPickable = false;
  81767. torus.parent = this._teleportationTarget;
  81768. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81769. var keys = [];
  81770. keys.push({
  81771. frame: 0,
  81772. value: 0
  81773. });
  81774. keys.push({
  81775. frame: 30,
  81776. value: 0.4
  81777. });
  81778. keys.push({
  81779. frame: 60,
  81780. value: 0
  81781. });
  81782. animationInnerCircle.setKeys(keys);
  81783. var easingFunction = new BABYLON.SineEase();
  81784. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81785. animationInnerCircle.setEasingFunction(easingFunction);
  81786. torus.animations = [];
  81787. torus.animations.push(animationInnerCircle);
  81788. this._scene.beginAnimation(torus, 0, 60, true);
  81789. this._hideTeleportationTarget();
  81790. };
  81791. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81792. this._teleportActive = true;
  81793. if (this._teleportationInitialized) {
  81794. this._teleportationTarget.isVisible = true;
  81795. if (this._isDefaultTeleportationTarget) {
  81796. this._teleportationTarget.getChildren()[0].isVisible = true;
  81797. }
  81798. }
  81799. };
  81800. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81801. this._teleportActive = false;
  81802. if (this._teleportationInitialized) {
  81803. this._teleportationTarget.isVisible = false;
  81804. if (this._isDefaultTeleportationTarget) {
  81805. this._teleportationTarget.getChildren()[0].isVisible = false;
  81806. }
  81807. }
  81808. };
  81809. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81810. var _this = this;
  81811. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81812. return;
  81813. }
  81814. if (right) {
  81815. this._rotationAngle++;
  81816. }
  81817. else {
  81818. this._rotationAngle--;
  81819. }
  81820. this.currentVRCamera.animations = [];
  81821. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81822. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81823. var animationRotationKeys = [];
  81824. animationRotationKeys.push({
  81825. frame: 0,
  81826. value: this.currentVRCamera.rotationQuaternion
  81827. });
  81828. animationRotationKeys.push({
  81829. frame: 6,
  81830. value: target
  81831. });
  81832. animationRotation.setKeys(animationRotationKeys);
  81833. animationRotation.setEasingFunction(this._circleEase);
  81834. this.currentVRCamera.animations.push(animationRotation);
  81835. this._postProcessMove.animations = [];
  81836. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81837. var vignetteWeightKeys = [];
  81838. vignetteWeightKeys.push({
  81839. frame: 0,
  81840. value: 0
  81841. });
  81842. vignetteWeightKeys.push({
  81843. frame: 3,
  81844. value: 4
  81845. });
  81846. vignetteWeightKeys.push({
  81847. frame: 6,
  81848. value: 0
  81849. });
  81850. animationPP.setKeys(vignetteWeightKeys);
  81851. animationPP.setEasingFunction(this._circleEase);
  81852. this._postProcessMove.animations.push(animationPP);
  81853. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81854. var vignetteStretchKeys = [];
  81855. vignetteStretchKeys.push({
  81856. frame: 0,
  81857. value: 0
  81858. });
  81859. vignetteStretchKeys.push({
  81860. frame: 3,
  81861. value: 10
  81862. });
  81863. vignetteStretchKeys.push({
  81864. frame: 6,
  81865. value: 0
  81866. });
  81867. animationPP2.setKeys(vignetteStretchKeys);
  81868. animationPP2.setEasingFunction(this._circleEase);
  81869. this._postProcessMove.animations.push(animationPP2);
  81870. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81871. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81872. this._postProcessMove.samples = 4;
  81873. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81874. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81875. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81876. });
  81877. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81878. };
  81879. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81880. if (hit.pickedPoint) {
  81881. if (gazer._teleportationRequestInitiated) {
  81882. this._displayTeleportationTarget();
  81883. this._haloCenter.copyFrom(hit.pickedPoint);
  81884. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81885. }
  81886. var pickNormal = hit.getNormal(true, false);
  81887. if (pickNormal) {
  81888. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81889. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81890. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81891. }
  81892. this._teleportationTarget.position.y += 0.1;
  81893. }
  81894. };
  81895. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81896. var _this = this;
  81897. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81898. return;
  81899. }
  81900. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81901. // offset of the headset from the anchor.
  81902. if (this.webVRCamera.leftCamera) {
  81903. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81904. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81905. location.subtractToRef(this._workingVector, this._workingVector);
  81906. }
  81907. else {
  81908. this._workingVector.copyFrom(location);
  81909. }
  81910. // Add height to account for user's height offset
  81911. if (this.isInVRMode) {
  81912. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  81913. }
  81914. else {
  81915. this._workingVector.y += this._defaultHeight;
  81916. }
  81917. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81918. // Create animation from the camera's position to the new location
  81919. this.currentVRCamera.animations = [];
  81920. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81921. var animationCameraTeleportationKeys = [{
  81922. frame: 0,
  81923. value: this.currentVRCamera.position
  81924. },
  81925. {
  81926. frame: 11,
  81927. value: this._workingVector
  81928. }
  81929. ];
  81930. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81931. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81932. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81933. this._postProcessMove.animations = [];
  81934. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81935. var vignetteWeightKeys = [];
  81936. vignetteWeightKeys.push({
  81937. frame: 0,
  81938. value: 0
  81939. });
  81940. vignetteWeightKeys.push({
  81941. frame: 5,
  81942. value: 8
  81943. });
  81944. vignetteWeightKeys.push({
  81945. frame: 11,
  81946. value: 0
  81947. });
  81948. animationPP.setKeys(vignetteWeightKeys);
  81949. this._postProcessMove.animations.push(animationPP);
  81950. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81951. var vignetteStretchKeys = [];
  81952. vignetteStretchKeys.push({
  81953. frame: 0,
  81954. value: 0
  81955. });
  81956. vignetteStretchKeys.push({
  81957. frame: 5,
  81958. value: 10
  81959. });
  81960. vignetteStretchKeys.push({
  81961. frame: 11,
  81962. value: 0
  81963. });
  81964. animationPP2.setKeys(vignetteStretchKeys);
  81965. this._postProcessMove.animations.push(animationPP2);
  81966. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81967. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81968. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81969. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81970. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81971. });
  81972. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81973. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81974. });
  81975. this._hideTeleportationTarget();
  81976. };
  81977. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81978. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81979. return;
  81980. }
  81981. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81982. // Moving the gazeTracker on the mesh face targetted
  81983. if (hit && hit.pickedPoint) {
  81984. if (this._displayGaze) {
  81985. var multiplier = 1;
  81986. gazer._gazeTracker.isVisible = true;
  81987. if (gazer._isActionableMesh) {
  81988. multiplier = 3;
  81989. }
  81990. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81991. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81992. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81993. var pickNormal = hit.getNormal();
  81994. // To avoid z-fighting
  81995. var deltaFighting = 0.002;
  81996. if (pickNormal) {
  81997. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81998. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81999. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82000. }
  82001. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82002. if (gazer._gazeTracker.position.x < 0) {
  82003. gazer._gazeTracker.position.x += deltaFighting;
  82004. }
  82005. else {
  82006. gazer._gazeTracker.position.x -= deltaFighting;
  82007. }
  82008. if (gazer._gazeTracker.position.y < 0) {
  82009. gazer._gazeTracker.position.y += deltaFighting;
  82010. }
  82011. else {
  82012. gazer._gazeTracker.position.y -= deltaFighting;
  82013. }
  82014. if (gazer._gazeTracker.position.z < 0) {
  82015. gazer._gazeTracker.position.z += deltaFighting;
  82016. }
  82017. else {
  82018. gazer._gazeTracker.position.z -= deltaFighting;
  82019. }
  82020. }
  82021. // Changing the size of the laser pointer based on the distance from the targetted point
  82022. gazer._updatePointerDistance(hit.distance);
  82023. }
  82024. else {
  82025. gazer._gazeTracker.isVisible = false;
  82026. }
  82027. if (hit && hit.pickedMesh) {
  82028. gazer._currentHit = hit;
  82029. if (gazer._pointerDownOnMeshAsked) {
  82030. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82031. }
  82032. // The object selected is the floor, we're in a teleportation scenario
  82033. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82034. // Moving the teleportation area to this targetted point
  82035. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82036. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82037. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82038. }
  82039. gazer._currentMeshSelected = null;
  82040. if (gazer._teleportationRequestInitiated) {
  82041. this._moveTeleportationSelectorTo(hit, gazer);
  82042. }
  82043. return;
  82044. }
  82045. // If not, we're in a selection scenario
  82046. //this._teleportationAllowed = false;
  82047. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82048. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82049. this.onNewMeshPicked.notifyObservers(hit);
  82050. gazer._currentMeshSelected = hit.pickedMesh;
  82051. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82052. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82053. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82054. gazer._isActionableMesh = true;
  82055. }
  82056. else {
  82057. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82058. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82059. gazer._isActionableMesh = false;
  82060. }
  82061. try {
  82062. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82063. }
  82064. catch (err) {
  82065. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82066. }
  82067. }
  82068. else {
  82069. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82070. gazer._currentMeshSelected = null;
  82071. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82072. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82073. }
  82074. }
  82075. }
  82076. else {
  82077. gazer._currentHit = null;
  82078. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82079. gazer._currentMeshSelected = null;
  82080. //this._teleportationAllowed = false;
  82081. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82082. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82083. }
  82084. };
  82085. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82086. if (mesh) {
  82087. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82088. }
  82089. };
  82090. /**
  82091. * Sets the color of the laser ray from the vr controllers.
  82092. * @param color new color for the ray.
  82093. */
  82094. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82095. if (this.leftController) {
  82096. this.leftController._setLaserPointerColor(color);
  82097. }
  82098. if (this.rightController) {
  82099. this.rightController._setLaserPointerColor(color);
  82100. }
  82101. };
  82102. /**
  82103. * Sets the color of the ray from the vr headsets gaze.
  82104. * @param color new color for the ray.
  82105. */
  82106. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82107. if (!this._cameraGazer._gazeTracker.material) {
  82108. return;
  82109. }
  82110. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82111. if (this.leftController) {
  82112. this.leftController._gazeTracker.material.emissiveColor = color;
  82113. }
  82114. if (this.rightController) {
  82115. this.rightController._gazeTracker.material.emissiveColor = color;
  82116. }
  82117. };
  82118. /**
  82119. * Exits VR and disposes of the vr experience helper
  82120. */
  82121. VRExperienceHelper.prototype.dispose = function () {
  82122. if (this.isInVRMode) {
  82123. this.exitVR();
  82124. }
  82125. if (this._postProcessMove) {
  82126. this._postProcessMove.dispose();
  82127. }
  82128. if (this._webVRCamera) {
  82129. this._webVRCamera.dispose();
  82130. }
  82131. if (this._vrDeviceOrientationCamera) {
  82132. this._vrDeviceOrientationCamera.dispose();
  82133. }
  82134. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82135. document.body.removeChild(this._btnVR);
  82136. }
  82137. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82138. this._deviceOrientationCamera.dispose();
  82139. }
  82140. if (this._cameraGazer) {
  82141. this._cameraGazer.dispose();
  82142. }
  82143. if (this.leftController) {
  82144. this.leftController.dispose();
  82145. }
  82146. if (this.rightController) {
  82147. this.rightController.dispose();
  82148. }
  82149. if (this._teleportationTarget) {
  82150. this._teleportationTarget.dispose();
  82151. }
  82152. this._floorMeshesCollection = [];
  82153. document.removeEventListener("keydown", this._onKeyDown);
  82154. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82155. window.removeEventListener("resize", this._onResize);
  82156. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82157. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82158. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82159. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82160. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82161. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82162. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82163. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82164. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82165. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82166. this._scene.unregisterBeforeRender(this.beforeRender);
  82167. };
  82168. /**
  82169. * Gets the name of the VRExperienceHelper class
  82170. * @returns "VRExperienceHelper"
  82171. */
  82172. VRExperienceHelper.prototype.getClassName = function () {
  82173. return "VRExperienceHelper";
  82174. };
  82175. return VRExperienceHelper;
  82176. }());
  82177. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82178. })(BABYLON || (BABYLON = {}));
  82179. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82180. // Mainly based on these 2 articles :
  82181. // 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
  82182. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82183. var BABYLON;
  82184. (function (BABYLON) {
  82185. var JoystickAxis;
  82186. (function (JoystickAxis) {
  82187. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82188. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82189. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82190. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82191. var VirtualJoystick = /** @class */ (function () {
  82192. function VirtualJoystick(leftJoystick) {
  82193. var _this = this;
  82194. if (leftJoystick) {
  82195. this._leftJoystick = true;
  82196. }
  82197. else {
  82198. this._leftJoystick = false;
  82199. }
  82200. VirtualJoystick._globalJoystickIndex++;
  82201. // By default left & right arrow keys are moving the X
  82202. // and up & down keys are moving the Y
  82203. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82204. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82205. this.reverseLeftRight = false;
  82206. this.reverseUpDown = false;
  82207. // collections of pointers
  82208. this._touches = new BABYLON.StringDictionary();
  82209. this.deltaPosition = BABYLON.Vector3.Zero();
  82210. this._joystickSensibility = 25;
  82211. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82212. this._onResize = function (evt) {
  82213. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82214. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82215. if (VirtualJoystick.vjCanvas) {
  82216. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82217. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82218. }
  82219. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82220. };
  82221. // injecting a canvas element on top of the canvas 3D game
  82222. if (!VirtualJoystick.vjCanvas) {
  82223. window.addEventListener("resize", this._onResize, false);
  82224. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82225. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82226. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82227. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82228. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82229. VirtualJoystick.vjCanvas.style.width = "100%";
  82230. VirtualJoystick.vjCanvas.style.height = "100%";
  82231. VirtualJoystick.vjCanvas.style.position = "absolute";
  82232. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82233. VirtualJoystick.vjCanvas.style.top = "0px";
  82234. VirtualJoystick.vjCanvas.style.left = "0px";
  82235. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82236. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82237. // Support for jQuery PEP polyfill
  82238. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82239. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82240. if (!context) {
  82241. throw new Error("Unable to create canvas for virtual joystick");
  82242. }
  82243. VirtualJoystick.vjCanvasContext = context;
  82244. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82245. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82246. document.body.appendChild(VirtualJoystick.vjCanvas);
  82247. }
  82248. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82249. this.pressed = false;
  82250. // default joystick color
  82251. this._joystickColor = "cyan";
  82252. this._joystickPointerID = -1;
  82253. // current joystick position
  82254. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82255. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82256. // origin joystick position
  82257. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82258. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82259. this._onPointerDownHandlerRef = function (evt) {
  82260. _this._onPointerDown(evt);
  82261. };
  82262. this._onPointerMoveHandlerRef = function (evt) {
  82263. _this._onPointerMove(evt);
  82264. };
  82265. this._onPointerUpHandlerRef = function (evt) {
  82266. _this._onPointerUp(evt);
  82267. };
  82268. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82269. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82270. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82271. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82272. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82273. evt.preventDefault(); // Disables system menu
  82274. }, false);
  82275. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82276. }
  82277. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82278. this._joystickSensibility = newJoystickSensibility;
  82279. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82280. };
  82281. VirtualJoystick.prototype._onPointerDown = function (e) {
  82282. var positionOnScreenCondition;
  82283. e.preventDefault();
  82284. if (this._leftJoystick === true) {
  82285. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82286. }
  82287. else {
  82288. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82289. }
  82290. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82291. // First contact will be dedicated to the virtual joystick
  82292. this._joystickPointerID = e.pointerId;
  82293. this._joystickPointerStartPos.x = e.clientX;
  82294. this._joystickPointerStartPos.y = e.clientY;
  82295. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82296. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82297. this._deltaJoystickVector.x = 0;
  82298. this._deltaJoystickVector.y = 0;
  82299. this.pressed = true;
  82300. this._touches.add(e.pointerId.toString(), e);
  82301. }
  82302. else {
  82303. // You can only trigger the action buttons with a joystick declared
  82304. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82305. this._action();
  82306. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82307. }
  82308. }
  82309. };
  82310. VirtualJoystick.prototype._onPointerMove = function (e) {
  82311. // If the current pointer is the one associated to the joystick (first touch contact)
  82312. if (this._joystickPointerID == e.pointerId) {
  82313. this._joystickPointerPos.x = e.clientX;
  82314. this._joystickPointerPos.y = e.clientY;
  82315. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82316. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82317. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82318. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82319. switch (this._axisTargetedByLeftAndRight) {
  82320. case JoystickAxis.X:
  82321. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82322. break;
  82323. case JoystickAxis.Y:
  82324. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82325. break;
  82326. case JoystickAxis.Z:
  82327. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82328. break;
  82329. }
  82330. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82331. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82332. switch (this._axisTargetedByUpAndDown) {
  82333. case JoystickAxis.X:
  82334. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82335. break;
  82336. case JoystickAxis.Y:
  82337. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82338. break;
  82339. case JoystickAxis.Z:
  82340. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82341. break;
  82342. }
  82343. }
  82344. else {
  82345. var data = this._touches.get(e.pointerId.toString());
  82346. if (data) {
  82347. data.x = e.clientX;
  82348. data.y = e.clientY;
  82349. }
  82350. }
  82351. };
  82352. VirtualJoystick.prototype._onPointerUp = function (e) {
  82353. if (this._joystickPointerID == e.pointerId) {
  82354. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82355. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82356. this._joystickPointerID = -1;
  82357. this.pressed = false;
  82358. }
  82359. else {
  82360. var touch = this._touches.get(e.pointerId.toString());
  82361. if (touch) {
  82362. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82363. }
  82364. }
  82365. this._deltaJoystickVector.x = 0;
  82366. this._deltaJoystickVector.y = 0;
  82367. this._touches.remove(e.pointerId.toString());
  82368. };
  82369. /**
  82370. * Change the color of the virtual joystick
  82371. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82372. */
  82373. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82374. this._joystickColor = newColor;
  82375. };
  82376. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82377. this._action = action;
  82378. };
  82379. // Define which axis you'd like to control for left & right
  82380. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82381. switch (axis) {
  82382. case JoystickAxis.X:
  82383. case JoystickAxis.Y:
  82384. case JoystickAxis.Z:
  82385. this._axisTargetedByLeftAndRight = axis;
  82386. break;
  82387. default:
  82388. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82389. break;
  82390. }
  82391. };
  82392. // Define which axis you'd like to control for up & down
  82393. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82394. switch (axis) {
  82395. case JoystickAxis.X:
  82396. case JoystickAxis.Y:
  82397. case JoystickAxis.Z:
  82398. this._axisTargetedByUpAndDown = axis;
  82399. break;
  82400. default:
  82401. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82402. break;
  82403. }
  82404. };
  82405. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82406. var _this = this;
  82407. if (this.pressed) {
  82408. this._touches.forEach(function (key, touch) {
  82409. if (touch.pointerId === _this._joystickPointerID) {
  82410. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82411. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82412. VirtualJoystick.vjCanvasContext.beginPath();
  82413. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82414. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82415. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82416. VirtualJoystick.vjCanvasContext.stroke();
  82417. VirtualJoystick.vjCanvasContext.closePath();
  82418. VirtualJoystick.vjCanvasContext.beginPath();
  82419. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82420. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82421. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82422. VirtualJoystick.vjCanvasContext.stroke();
  82423. VirtualJoystick.vjCanvasContext.closePath();
  82424. VirtualJoystick.vjCanvasContext.beginPath();
  82425. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82426. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82427. VirtualJoystick.vjCanvasContext.stroke();
  82428. VirtualJoystick.vjCanvasContext.closePath();
  82429. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82430. }
  82431. else {
  82432. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82433. VirtualJoystick.vjCanvasContext.beginPath();
  82434. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82435. VirtualJoystick.vjCanvasContext.beginPath();
  82436. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82437. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82438. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82439. VirtualJoystick.vjCanvasContext.stroke();
  82440. VirtualJoystick.vjCanvasContext.closePath();
  82441. touch.prevX = touch.x;
  82442. touch.prevY = touch.y;
  82443. }
  82444. ;
  82445. });
  82446. }
  82447. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82448. };
  82449. VirtualJoystick.prototype.releaseCanvas = function () {
  82450. if (VirtualJoystick.vjCanvas) {
  82451. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82452. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82453. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82454. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82455. window.removeEventListener("resize", this._onResize);
  82456. document.body.removeChild(VirtualJoystick.vjCanvas);
  82457. VirtualJoystick.vjCanvas = null;
  82458. }
  82459. };
  82460. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82461. VirtualJoystick._globalJoystickIndex = 0;
  82462. return VirtualJoystick;
  82463. }());
  82464. BABYLON.VirtualJoystick = VirtualJoystick;
  82465. })(BABYLON || (BABYLON = {}));
  82466. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82467. var BABYLON;
  82468. (function (BABYLON) {
  82469. // We're mainly based on the logic defined into the FreeCamera code
  82470. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82471. __extends(VirtualJoysticksCamera, _super);
  82472. function VirtualJoysticksCamera(name, position, scene) {
  82473. var _this = _super.call(this, name, position, scene) || this;
  82474. _this.inputs.addVirtualJoystick();
  82475. return _this;
  82476. }
  82477. VirtualJoysticksCamera.prototype.getClassName = function () {
  82478. return "VirtualJoysticksCamera";
  82479. };
  82480. return VirtualJoysticksCamera;
  82481. }(BABYLON.FreeCamera));
  82482. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82483. })(BABYLON || (BABYLON = {}));
  82484. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82485. var BABYLON;
  82486. (function (BABYLON) {
  82487. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82488. function FreeCameraVirtualJoystickInput() {
  82489. }
  82490. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82491. return this._leftjoystick;
  82492. };
  82493. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82494. return this._rightjoystick;
  82495. };
  82496. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82497. if (this._leftjoystick) {
  82498. var camera = this.camera;
  82499. var speed = camera._computeLocalCameraSpeed() * 50;
  82500. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82501. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82502. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82503. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82504. if (!this._leftjoystick.pressed) {
  82505. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82506. }
  82507. if (!this._rightjoystick.pressed) {
  82508. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82509. }
  82510. }
  82511. };
  82512. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82513. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82514. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82515. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82516. this._leftjoystick.setJoystickSensibility(0.15);
  82517. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82518. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82519. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82520. this._rightjoystick.reverseUpDown = true;
  82521. this._rightjoystick.setJoystickSensibility(0.05);
  82522. this._rightjoystick.setJoystickColor("yellow");
  82523. };
  82524. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82525. this._leftjoystick.releaseCanvas();
  82526. this._rightjoystick.releaseCanvas();
  82527. };
  82528. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82529. return "FreeCameraVirtualJoystickInput";
  82530. };
  82531. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82532. return "virtualJoystick";
  82533. };
  82534. return FreeCameraVirtualJoystickInput;
  82535. }());
  82536. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82537. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82538. })(BABYLON || (BABYLON = {}));
  82539. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82540. var BABYLON;
  82541. (function (BABYLON) {
  82542. var SimplificationSettings = /** @class */ (function () {
  82543. function SimplificationSettings(quality, distance, optimizeMesh) {
  82544. this.quality = quality;
  82545. this.distance = distance;
  82546. this.optimizeMesh = optimizeMesh;
  82547. }
  82548. return SimplificationSettings;
  82549. }());
  82550. BABYLON.SimplificationSettings = SimplificationSettings;
  82551. var SimplificationQueue = /** @class */ (function () {
  82552. function SimplificationQueue() {
  82553. this.running = false;
  82554. this._simplificationArray = [];
  82555. }
  82556. SimplificationQueue.prototype.addTask = function (task) {
  82557. this._simplificationArray.push(task);
  82558. };
  82559. SimplificationQueue.prototype.executeNext = function () {
  82560. var task = this._simplificationArray.pop();
  82561. if (task) {
  82562. this.running = true;
  82563. this.runSimplification(task);
  82564. }
  82565. else {
  82566. this.running = false;
  82567. }
  82568. };
  82569. SimplificationQueue.prototype.runSimplification = function (task) {
  82570. var _this = this;
  82571. if (task.parallelProcessing) {
  82572. //parallel simplifier
  82573. task.settings.forEach(function (setting) {
  82574. var simplifier = _this.getSimplifier(task);
  82575. simplifier.simplify(setting, function (newMesh) {
  82576. task.mesh.addLODLevel(setting.distance, newMesh);
  82577. newMesh.isVisible = true;
  82578. //check if it is the last
  82579. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82580. //all done, run the success callback.
  82581. task.successCallback();
  82582. }
  82583. _this.executeNext();
  82584. });
  82585. });
  82586. }
  82587. else {
  82588. //single simplifier.
  82589. var simplifier = this.getSimplifier(task);
  82590. var runDecimation = function (setting, callback) {
  82591. simplifier.simplify(setting, function (newMesh) {
  82592. task.mesh.addLODLevel(setting.distance, newMesh);
  82593. newMesh.isVisible = true;
  82594. //run the next quality level
  82595. callback();
  82596. });
  82597. };
  82598. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82599. runDecimation(task.settings[loop.index], function () {
  82600. loop.executeNext();
  82601. });
  82602. }, function () {
  82603. //execution ended, run the success callback.
  82604. if (task.successCallback) {
  82605. task.successCallback();
  82606. }
  82607. _this.executeNext();
  82608. });
  82609. }
  82610. };
  82611. SimplificationQueue.prototype.getSimplifier = function (task) {
  82612. switch (task.simplificationType) {
  82613. case SimplificationType.QUADRATIC:
  82614. default:
  82615. return new QuadraticErrorSimplification(task.mesh);
  82616. }
  82617. };
  82618. return SimplificationQueue;
  82619. }());
  82620. BABYLON.SimplificationQueue = SimplificationQueue;
  82621. /**
  82622. * The implemented types of simplification.
  82623. * At the moment only Quadratic Error Decimation is implemented.
  82624. */
  82625. var SimplificationType;
  82626. (function (SimplificationType) {
  82627. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82628. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82629. var DecimationTriangle = /** @class */ (function () {
  82630. function DecimationTriangle(vertices) {
  82631. this.vertices = vertices;
  82632. this.error = new Array(4);
  82633. this.deleted = false;
  82634. this.isDirty = false;
  82635. this.deletePending = false;
  82636. this.borderFactor = 0;
  82637. }
  82638. return DecimationTriangle;
  82639. }());
  82640. BABYLON.DecimationTriangle = DecimationTriangle;
  82641. var DecimationVertex = /** @class */ (function () {
  82642. function DecimationVertex(position, id) {
  82643. this.position = position;
  82644. this.id = id;
  82645. this.isBorder = true;
  82646. this.q = new QuadraticMatrix();
  82647. this.triangleCount = 0;
  82648. this.triangleStart = 0;
  82649. this.originalOffsets = [];
  82650. }
  82651. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82652. this.position.copyFrom(newPosition);
  82653. };
  82654. return DecimationVertex;
  82655. }());
  82656. BABYLON.DecimationVertex = DecimationVertex;
  82657. var QuadraticMatrix = /** @class */ (function () {
  82658. function QuadraticMatrix(data) {
  82659. this.data = new Array(10);
  82660. for (var i = 0; i < 10; ++i) {
  82661. if (data && data[i]) {
  82662. this.data[i] = data[i];
  82663. }
  82664. else {
  82665. this.data[i] = 0;
  82666. }
  82667. }
  82668. }
  82669. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82670. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82671. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82672. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82673. return det;
  82674. };
  82675. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82676. for (var i = 0; i < 10; ++i) {
  82677. this.data[i] += matrix.data[i];
  82678. }
  82679. };
  82680. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82681. for (var i = 0; i < 10; ++i) {
  82682. this.data[i] += data[i];
  82683. }
  82684. };
  82685. QuadraticMatrix.prototype.add = function (matrix) {
  82686. var m = new QuadraticMatrix();
  82687. for (var i = 0; i < 10; ++i) {
  82688. m.data[i] = this.data[i] + matrix.data[i];
  82689. }
  82690. return m;
  82691. };
  82692. QuadraticMatrix.FromData = function (a, b, c, d) {
  82693. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82694. };
  82695. //returning an array to avoid garbage collection
  82696. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82697. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82698. };
  82699. return QuadraticMatrix;
  82700. }());
  82701. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82702. var Reference = /** @class */ (function () {
  82703. function Reference(vertexId, triangleId) {
  82704. this.vertexId = vertexId;
  82705. this.triangleId = triangleId;
  82706. }
  82707. return Reference;
  82708. }());
  82709. BABYLON.Reference = Reference;
  82710. /**
  82711. * An implementation of the Quadratic Error simplification algorithm.
  82712. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82713. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82714. * @author RaananW
  82715. */
  82716. var QuadraticErrorSimplification = /** @class */ (function () {
  82717. function QuadraticErrorSimplification(_mesh) {
  82718. this._mesh = _mesh;
  82719. this.syncIterations = 5000;
  82720. this.aggressiveness = 7;
  82721. this.decimationIterations = 100;
  82722. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82723. }
  82724. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82725. var _this = this;
  82726. this.initDecimatedMesh();
  82727. //iterating through the submeshes array, one after the other.
  82728. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82729. _this.initWithMesh(loop.index, function () {
  82730. _this.runDecimation(settings, loop.index, function () {
  82731. loop.executeNext();
  82732. });
  82733. }, settings.optimizeMesh);
  82734. }, function () {
  82735. setTimeout(function () {
  82736. successCallback(_this._reconstructedMesh);
  82737. }, 0);
  82738. });
  82739. };
  82740. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82741. var _this = this;
  82742. var targetCount = ~~(this.triangles.length * settings.quality);
  82743. var deletedTriangles = 0;
  82744. var triangleCount = this.triangles.length;
  82745. var iterationFunction = function (iteration, callback) {
  82746. setTimeout(function () {
  82747. if (iteration % 5 === 0) {
  82748. _this.updateMesh(iteration === 0);
  82749. }
  82750. for (var i = 0; i < _this.triangles.length; ++i) {
  82751. _this.triangles[i].isDirty = false;
  82752. }
  82753. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82754. var trianglesIterator = function (i) {
  82755. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82756. var t = _this.triangles[tIdx];
  82757. if (!t)
  82758. return;
  82759. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82760. return;
  82761. }
  82762. for (var j = 0; j < 3; ++j) {
  82763. if (t.error[j] < threshold) {
  82764. var deleted0 = [];
  82765. var deleted1 = [];
  82766. var v0 = t.vertices[j];
  82767. var v1 = t.vertices[(j + 1) % 3];
  82768. if (v0.isBorder || v1.isBorder)
  82769. continue;
  82770. var p = BABYLON.Vector3.Zero();
  82771. var n = BABYLON.Vector3.Zero();
  82772. var uv = BABYLON.Vector2.Zero();
  82773. var color = new BABYLON.Color4(0, 0, 0, 1);
  82774. _this.calculateError(v0, v1, p, n, uv, color);
  82775. var delTr = new Array();
  82776. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82777. continue;
  82778. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82779. continue;
  82780. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82781. continue;
  82782. var uniqueArray = new Array();
  82783. delTr.forEach(function (deletedT) {
  82784. if (uniqueArray.indexOf(deletedT) === -1) {
  82785. deletedT.deletePending = true;
  82786. uniqueArray.push(deletedT);
  82787. }
  82788. });
  82789. if (uniqueArray.length % 2 !== 0) {
  82790. continue;
  82791. }
  82792. v0.q = v1.q.add(v0.q);
  82793. v0.updatePosition(p);
  82794. var tStart = _this.references.length;
  82795. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82796. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82797. var tCount = _this.references.length - tStart;
  82798. if (tCount <= v0.triangleCount) {
  82799. if (tCount) {
  82800. for (var c = 0; c < tCount; c++) {
  82801. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82802. }
  82803. }
  82804. }
  82805. else {
  82806. v0.triangleStart = tStart;
  82807. }
  82808. v0.triangleCount = tCount;
  82809. break;
  82810. }
  82811. }
  82812. };
  82813. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82814. }, 0);
  82815. };
  82816. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82817. if (triangleCount - deletedTriangles <= targetCount)
  82818. loop.breakLoop();
  82819. else {
  82820. iterationFunction(loop.index, function () {
  82821. loop.executeNext();
  82822. });
  82823. }
  82824. }, function () {
  82825. setTimeout(function () {
  82826. //reconstruct this part of the mesh
  82827. _this.reconstructMesh(submeshIndex);
  82828. successCallback();
  82829. }, 0);
  82830. });
  82831. };
  82832. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82833. var _this = this;
  82834. this.vertices = [];
  82835. this.triangles = [];
  82836. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82837. var indices = this._mesh.getIndices();
  82838. var submesh = this._mesh.subMeshes[submeshIndex];
  82839. var findInVertices = function (positionToSearch) {
  82840. if (optimizeMesh) {
  82841. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82842. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82843. return _this.vertices[ii];
  82844. }
  82845. }
  82846. }
  82847. return null;
  82848. };
  82849. var vertexReferences = [];
  82850. var vertexInit = function (i) {
  82851. if (!positionData) {
  82852. return;
  82853. }
  82854. var offset = i + submesh.verticesStart;
  82855. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82856. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82857. vertex.originalOffsets.push(offset);
  82858. if (vertex.id === _this.vertices.length) {
  82859. _this.vertices.push(vertex);
  82860. }
  82861. vertexReferences.push(vertex.id);
  82862. };
  82863. //var totalVertices = mesh.getTotalVertices();
  82864. var totalVertices = submesh.verticesCount;
  82865. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82866. var indicesInit = function (i) {
  82867. if (!indices) {
  82868. return;
  82869. }
  82870. var offset = (submesh.indexStart / 3) + i;
  82871. var pos = (offset * 3);
  82872. var i0 = indices[pos + 0];
  82873. var i1 = indices[pos + 1];
  82874. var i2 = indices[pos + 2];
  82875. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82876. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82877. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82878. var triangle = new DecimationTriangle([v0, v1, v2]);
  82879. triangle.originalOffset = pos;
  82880. _this.triangles.push(triangle);
  82881. };
  82882. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82883. _this.init(callback);
  82884. });
  82885. });
  82886. };
  82887. QuadraticErrorSimplification.prototype.init = function (callback) {
  82888. var _this = this;
  82889. var triangleInit1 = function (i) {
  82890. var t = _this.triangles[i];
  82891. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82892. for (var j = 0; j < 3; j++) {
  82893. 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))));
  82894. }
  82895. };
  82896. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82897. var triangleInit2 = function (i) {
  82898. var t = _this.triangles[i];
  82899. for (var j = 0; j < 3; ++j) {
  82900. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82901. }
  82902. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82903. };
  82904. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82905. callback();
  82906. });
  82907. });
  82908. };
  82909. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82910. var newTriangles = [];
  82911. var i;
  82912. for (i = 0; i < this.vertices.length; ++i) {
  82913. this.vertices[i].triangleCount = 0;
  82914. }
  82915. var t;
  82916. var j;
  82917. for (i = 0; i < this.triangles.length; ++i) {
  82918. if (!this.triangles[i].deleted) {
  82919. t = this.triangles[i];
  82920. for (j = 0; j < 3; ++j) {
  82921. t.vertices[j].triangleCount = 1;
  82922. }
  82923. newTriangles.push(t);
  82924. }
  82925. }
  82926. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82927. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82928. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82929. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82930. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82931. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82932. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82933. var vertexCount = 0;
  82934. for (i = 0; i < this.vertices.length; ++i) {
  82935. var vertex = this.vertices[i];
  82936. vertex.id = vertexCount;
  82937. if (vertex.triangleCount) {
  82938. vertex.originalOffsets.forEach(function (originalOffset) {
  82939. if (!normalData) {
  82940. return;
  82941. }
  82942. newPositionData.push(vertex.position.x);
  82943. newPositionData.push(vertex.position.y);
  82944. newPositionData.push(vertex.position.z);
  82945. newNormalData.push(normalData[originalOffset * 3]);
  82946. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82947. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82948. if (uvs && uvs.length) {
  82949. newUVsData.push(uvs[(originalOffset * 2)]);
  82950. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82951. }
  82952. else if (colorsData && colorsData.length) {
  82953. newColorsData.push(colorsData[(originalOffset * 4)]);
  82954. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82955. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82956. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82957. }
  82958. ++vertexCount;
  82959. });
  82960. }
  82961. }
  82962. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82963. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82964. var submeshesArray = this._reconstructedMesh.subMeshes;
  82965. this._reconstructedMesh.subMeshes = [];
  82966. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82967. var originalIndices = this._mesh.getIndices();
  82968. for (i = 0; i < newTriangles.length; ++i) {
  82969. t = newTriangles[i]; //now get the new referencing point for each vertex
  82970. [0, 1, 2].forEach(function (idx) {
  82971. var id = originalIndices[t.originalOffset + idx];
  82972. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82973. if (offset < 0)
  82974. offset = 0;
  82975. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82976. });
  82977. }
  82978. //overwriting the old vertex buffers and indices.
  82979. this._reconstructedMesh.setIndices(newIndicesArray);
  82980. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82981. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82982. if (newUVsData.length > 0)
  82983. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82984. if (newColorsData.length > 0)
  82985. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82986. //create submesh
  82987. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82988. if (submeshIndex > 0) {
  82989. this._reconstructedMesh.subMeshes = [];
  82990. submeshesArray.forEach(function (submesh) {
  82991. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82992. });
  82993. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82994. }
  82995. };
  82996. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82997. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82998. this._reconstructedMesh.material = this._mesh.material;
  82999. this._reconstructedMesh.parent = this._mesh.parent;
  83000. this._reconstructedMesh.isVisible = false;
  83001. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83002. };
  83003. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83004. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83005. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83006. if (t.deleted)
  83007. continue;
  83008. var s = this.references[vertex1.triangleStart + i].vertexId;
  83009. var v1 = t.vertices[(s + 1) % 3];
  83010. var v2 = t.vertices[(s + 2) % 3];
  83011. if ((v1 === vertex2 || v2 === vertex2)) {
  83012. deletedArray[i] = true;
  83013. delTr.push(t);
  83014. continue;
  83015. }
  83016. var d1 = v1.position.subtract(point);
  83017. d1 = d1.normalize();
  83018. var d2 = v2.position.subtract(point);
  83019. d2 = d2.normalize();
  83020. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83021. return true;
  83022. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83023. deletedArray[i] = false;
  83024. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83025. return true;
  83026. }
  83027. return false;
  83028. };
  83029. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83030. var newDeleted = deletedTriangles;
  83031. for (var i = 0; i < vertex.triangleCount; ++i) {
  83032. var ref = this.references[vertex.triangleStart + i];
  83033. var t = this.triangles[ref.triangleId];
  83034. if (t.deleted)
  83035. continue;
  83036. if (deletedArray[i] && t.deletePending) {
  83037. t.deleted = true;
  83038. newDeleted++;
  83039. continue;
  83040. }
  83041. t.vertices[ref.vertexId] = origVertex;
  83042. t.isDirty = true;
  83043. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83044. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83045. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83046. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83047. this.references.push(ref);
  83048. }
  83049. return newDeleted;
  83050. };
  83051. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83052. for (var i = 0; i < this.vertices.length; ++i) {
  83053. var vCount = [];
  83054. var vId = [];
  83055. var v = this.vertices[i];
  83056. var j;
  83057. for (j = 0; j < v.triangleCount; ++j) {
  83058. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83059. for (var ii = 0; ii < 3; ii++) {
  83060. var ofs = 0;
  83061. var vv = triangle.vertices[ii];
  83062. while (ofs < vCount.length) {
  83063. if (vId[ofs] === vv.id)
  83064. break;
  83065. ++ofs;
  83066. }
  83067. if (ofs === vCount.length) {
  83068. vCount.push(1);
  83069. vId.push(vv.id);
  83070. }
  83071. else {
  83072. vCount[ofs]++;
  83073. }
  83074. }
  83075. }
  83076. for (j = 0; j < vCount.length; ++j) {
  83077. if (vCount[j] === 1) {
  83078. this.vertices[vId[j]].isBorder = true;
  83079. }
  83080. else {
  83081. this.vertices[vId[j]].isBorder = false;
  83082. }
  83083. }
  83084. }
  83085. };
  83086. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83087. if (identifyBorders === void 0) { identifyBorders = false; }
  83088. var i;
  83089. if (!identifyBorders) {
  83090. var newTrianglesVector = [];
  83091. for (i = 0; i < this.triangles.length; ++i) {
  83092. if (!this.triangles[i].deleted) {
  83093. newTrianglesVector.push(this.triangles[i]);
  83094. }
  83095. }
  83096. this.triangles = newTrianglesVector;
  83097. }
  83098. for (i = 0; i < this.vertices.length; ++i) {
  83099. this.vertices[i].triangleCount = 0;
  83100. this.vertices[i].triangleStart = 0;
  83101. }
  83102. var t;
  83103. var j;
  83104. var v;
  83105. for (i = 0; i < this.triangles.length; ++i) {
  83106. t = this.triangles[i];
  83107. for (j = 0; j < 3; ++j) {
  83108. v = t.vertices[j];
  83109. v.triangleCount++;
  83110. }
  83111. }
  83112. var tStart = 0;
  83113. for (i = 0; i < this.vertices.length; ++i) {
  83114. this.vertices[i].triangleStart = tStart;
  83115. tStart += this.vertices[i].triangleCount;
  83116. this.vertices[i].triangleCount = 0;
  83117. }
  83118. var newReferences = new Array(this.triangles.length * 3);
  83119. for (i = 0; i < this.triangles.length; ++i) {
  83120. t = this.triangles[i];
  83121. for (j = 0; j < 3; ++j) {
  83122. v = t.vertices[j];
  83123. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83124. v.triangleCount++;
  83125. }
  83126. }
  83127. this.references = newReferences;
  83128. if (identifyBorders) {
  83129. this.identifyBorder();
  83130. }
  83131. };
  83132. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83133. var x = point.x;
  83134. var y = point.y;
  83135. var z = point.z;
  83136. 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
  83137. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83138. };
  83139. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83140. var q = vertex1.q.add(vertex2.q);
  83141. var border = vertex1.isBorder && vertex2.isBorder;
  83142. var error = 0;
  83143. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83144. if (qDet !== 0 && !border) {
  83145. if (!pointResult) {
  83146. pointResult = BABYLON.Vector3.Zero();
  83147. }
  83148. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83149. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83150. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83151. error = this.vertexError(q, pointResult);
  83152. }
  83153. else {
  83154. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83155. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83156. var error1 = this.vertexError(q, vertex1.position);
  83157. var error2 = this.vertexError(q, vertex2.position);
  83158. var error3 = this.vertexError(q, p3);
  83159. error = Math.min(error1, error2, error3);
  83160. if (error === error1) {
  83161. if (pointResult) {
  83162. pointResult.copyFrom(vertex1.position);
  83163. }
  83164. }
  83165. else if (error === error2) {
  83166. if (pointResult) {
  83167. pointResult.copyFrom(vertex2.position);
  83168. }
  83169. }
  83170. else {
  83171. if (pointResult) {
  83172. pointResult.copyFrom(p3);
  83173. }
  83174. }
  83175. }
  83176. return error;
  83177. };
  83178. return QuadraticErrorSimplification;
  83179. }());
  83180. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83181. })(BABYLON || (BABYLON = {}));
  83182. //# sourceMappingURL=babylon.meshSimplification.js.map
  83183. var BABYLON;
  83184. (function (BABYLON) {
  83185. var MeshLODLevel = /** @class */ (function () {
  83186. function MeshLODLevel(distance, mesh) {
  83187. this.distance = distance;
  83188. this.mesh = mesh;
  83189. }
  83190. return MeshLODLevel;
  83191. }());
  83192. BABYLON.MeshLODLevel = MeshLODLevel;
  83193. })(BABYLON || (BABYLON = {}));
  83194. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83195. var BABYLON;
  83196. (function (BABYLON) {
  83197. /**
  83198. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83199. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83200. */
  83201. var SceneOptimization = /** @class */ (function () {
  83202. /**
  83203. * Creates the SceneOptimization object
  83204. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83205. * @param desc defines the description associated with the optimization
  83206. */
  83207. function SceneOptimization(
  83208. /**
  83209. * Defines the priority of this optimization (0 by default which means first in the list)
  83210. */
  83211. priority) {
  83212. if (priority === void 0) { priority = 0; }
  83213. this.priority = priority;
  83214. }
  83215. /**
  83216. * Gets a string describing the action executed by the current optimization
  83217. * @returns description string
  83218. */
  83219. SceneOptimization.prototype.getDescription = function () {
  83220. return "";
  83221. };
  83222. /**
  83223. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83224. * @param scene defines the current scene where to apply this optimization
  83225. * @param optimizer defines the current optimizer
  83226. * @returns true if everything that can be done was applied
  83227. */
  83228. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83229. return true;
  83230. };
  83231. ;
  83232. return SceneOptimization;
  83233. }());
  83234. BABYLON.SceneOptimization = SceneOptimization;
  83235. /**
  83236. * Defines an optimization used to reduce the size of render target textures
  83237. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83238. */
  83239. var TextureOptimization = /** @class */ (function (_super) {
  83240. __extends(TextureOptimization, _super);
  83241. /**
  83242. * Creates the TextureOptimization object
  83243. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83244. * @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
  83245. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83246. */
  83247. function TextureOptimization(
  83248. /**
  83249. * Defines the priority of this optimization (0 by default which means first in the list)
  83250. */
  83251. priority,
  83252. /**
  83253. * 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
  83254. */
  83255. maximumSize,
  83256. /**
  83257. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83258. */
  83259. step) {
  83260. if (priority === void 0) { priority = 0; }
  83261. if (maximumSize === void 0) { maximumSize = 1024; }
  83262. if (step === void 0) { step = 0.5; }
  83263. var _this = _super.call(this, priority) || this;
  83264. _this.priority = priority;
  83265. _this.maximumSize = maximumSize;
  83266. _this.step = step;
  83267. return _this;
  83268. }
  83269. /**
  83270. * Gets a string describing the action executed by the current optimization
  83271. * @returns description string
  83272. */
  83273. TextureOptimization.prototype.getDescription = function () {
  83274. return "Reducing render target texture size to " + this.maximumSize;
  83275. };
  83276. /**
  83277. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83278. * @param scene defines the current scene where to apply this optimization
  83279. * @param optimizer defines the current optimizer
  83280. * @returns true if everything that can be done was applied
  83281. */
  83282. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83283. var allDone = true;
  83284. for (var index = 0; index < scene.textures.length; index++) {
  83285. var texture = scene.textures[index];
  83286. if (!texture.canRescale || texture.getContext) {
  83287. continue;
  83288. }
  83289. var currentSize = texture.getSize();
  83290. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83291. if (maxDimension > this.maximumSize) {
  83292. texture.scale(this.step);
  83293. allDone = false;
  83294. }
  83295. }
  83296. return allDone;
  83297. };
  83298. return TextureOptimization;
  83299. }(SceneOptimization));
  83300. BABYLON.TextureOptimization = TextureOptimization;
  83301. /**
  83302. * Defines an optimization used to increase or decrease the rendering resolution
  83303. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83304. */
  83305. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83306. __extends(HardwareScalingOptimization, _super);
  83307. /**
  83308. * Creates the HardwareScalingOptimization object
  83309. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83310. * @param maximumScale defines the maximum scale to use (2 by default)
  83311. * @param step defines the step to use between two passes (0.5 by default)
  83312. */
  83313. function HardwareScalingOptimization(
  83314. /**
  83315. * Defines the priority of this optimization (0 by default which means first in the list)
  83316. */
  83317. priority,
  83318. /**
  83319. * Defines the maximum scale to use (2 by default)
  83320. */
  83321. maximumScale,
  83322. /**
  83323. * Defines the step to use between two passes (0.5 by default)
  83324. */
  83325. step) {
  83326. if (priority === void 0) { priority = 0; }
  83327. if (maximumScale === void 0) { maximumScale = 2; }
  83328. if (step === void 0) { step = 0.25; }
  83329. var _this = _super.call(this, priority) || this;
  83330. _this.priority = priority;
  83331. _this.maximumScale = maximumScale;
  83332. _this.step = step;
  83333. _this._currentScale = -1;
  83334. _this._directionOffset = 1;
  83335. return _this;
  83336. }
  83337. /**
  83338. * Gets a string describing the action executed by the current optimization
  83339. * @return description string
  83340. */
  83341. HardwareScalingOptimization.prototype.getDescription = function () {
  83342. return "Setting hardware scaling level to " + this._currentScale;
  83343. };
  83344. /**
  83345. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83346. * @param scene defines the current scene where to apply this optimization
  83347. * @param optimizer defines the current optimizer
  83348. * @returns true if everything that can be done was applied
  83349. */
  83350. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83351. if (this._currentScale === -1) {
  83352. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83353. if (this._currentScale > this.maximumScale) {
  83354. this._directionOffset = -1;
  83355. }
  83356. }
  83357. this._currentScale += this._directionOffset * this.step;
  83358. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83359. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83360. };
  83361. ;
  83362. return HardwareScalingOptimization;
  83363. }(SceneOptimization));
  83364. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83365. /**
  83366. * Defines an optimization used to remove shadows
  83367. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83368. */
  83369. var ShadowsOptimization = /** @class */ (function (_super) {
  83370. __extends(ShadowsOptimization, _super);
  83371. function ShadowsOptimization() {
  83372. return _super !== null && _super.apply(this, arguments) || this;
  83373. }
  83374. /**
  83375. * Gets a string describing the action executed by the current optimization
  83376. * @return description string
  83377. */
  83378. ShadowsOptimization.prototype.getDescription = function () {
  83379. return "Turning shadows on/off";
  83380. };
  83381. /**
  83382. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83383. * @param scene defines the current scene where to apply this optimization
  83384. * @param optimizer defines the current optimizer
  83385. * @returns true if everything that can be done was applied
  83386. */
  83387. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83388. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83389. return true;
  83390. };
  83391. ;
  83392. return ShadowsOptimization;
  83393. }(SceneOptimization));
  83394. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83395. /**
  83396. * Defines an optimization used to turn post-processes off
  83397. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83398. */
  83399. var PostProcessesOptimization = /** @class */ (function (_super) {
  83400. __extends(PostProcessesOptimization, _super);
  83401. function PostProcessesOptimization() {
  83402. return _super !== null && _super.apply(this, arguments) || this;
  83403. }
  83404. /**
  83405. * Gets a string describing the action executed by the current optimization
  83406. * @return description string
  83407. */
  83408. PostProcessesOptimization.prototype.getDescription = function () {
  83409. return "Turning post-processes on/off";
  83410. };
  83411. /**
  83412. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83413. * @param scene defines the current scene where to apply this optimization
  83414. * @param optimizer defines the current optimizer
  83415. * @returns true if everything that can be done was applied
  83416. */
  83417. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83418. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83419. return true;
  83420. };
  83421. ;
  83422. return PostProcessesOptimization;
  83423. }(SceneOptimization));
  83424. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83425. /**
  83426. * Defines an optimization used to turn lens flares off
  83427. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83428. */
  83429. var LensFlaresOptimization = /** @class */ (function (_super) {
  83430. __extends(LensFlaresOptimization, _super);
  83431. function LensFlaresOptimization() {
  83432. return _super !== null && _super.apply(this, arguments) || this;
  83433. }
  83434. /**
  83435. * Gets a string describing the action executed by the current optimization
  83436. * @return description string
  83437. */
  83438. LensFlaresOptimization.prototype.getDescription = function () {
  83439. return "Turning lens flares on/off";
  83440. };
  83441. /**
  83442. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83443. * @param scene defines the current scene where to apply this optimization
  83444. * @param optimizer defines the current optimizer
  83445. * @returns true if everything that can be done was applied
  83446. */
  83447. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83448. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83449. return true;
  83450. };
  83451. ;
  83452. return LensFlaresOptimization;
  83453. }(SceneOptimization));
  83454. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83455. /**
  83456. * Defines an optimization based on user defined callback.
  83457. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83458. */
  83459. var CustomOptimization = /** @class */ (function (_super) {
  83460. __extends(CustomOptimization, _super);
  83461. function CustomOptimization() {
  83462. return _super !== null && _super.apply(this, arguments) || this;
  83463. }
  83464. /**
  83465. * Gets a string describing the action executed by the current optimization
  83466. * @returns description string
  83467. */
  83468. CustomOptimization.prototype.getDescription = function () {
  83469. if (this.onGetDescription) {
  83470. return this.onGetDescription();
  83471. }
  83472. return "Running user defined callback";
  83473. };
  83474. /**
  83475. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83476. * @param scene defines the current scene where to apply this optimization
  83477. * @param optimizer defines the current optimizer
  83478. * @returns true if everything that can be done was applied
  83479. */
  83480. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83481. if (this.onApply) {
  83482. return this.onApply(scene, optimizer);
  83483. }
  83484. return true;
  83485. };
  83486. ;
  83487. return CustomOptimization;
  83488. }(SceneOptimization));
  83489. BABYLON.CustomOptimization = CustomOptimization;
  83490. /**
  83491. * Defines an optimization used to turn particles off
  83492. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83493. */
  83494. var ParticlesOptimization = /** @class */ (function (_super) {
  83495. __extends(ParticlesOptimization, _super);
  83496. function ParticlesOptimization() {
  83497. return _super !== null && _super.apply(this, arguments) || this;
  83498. }
  83499. /**
  83500. * Gets a string describing the action executed by the current optimization
  83501. * @return description string
  83502. */
  83503. ParticlesOptimization.prototype.getDescription = function () {
  83504. return "Turning particles on/off";
  83505. };
  83506. /**
  83507. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83508. * @param scene defines the current scene where to apply this optimization
  83509. * @param optimizer defines the current optimizer
  83510. * @returns true if everything that can be done was applied
  83511. */
  83512. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83513. scene.particlesEnabled = optimizer.isInImprovementMode;
  83514. return true;
  83515. };
  83516. ;
  83517. return ParticlesOptimization;
  83518. }(SceneOptimization));
  83519. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83520. /**
  83521. * Defines an optimization used to turn render targets off
  83522. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83523. */
  83524. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83525. __extends(RenderTargetsOptimization, _super);
  83526. function RenderTargetsOptimization() {
  83527. return _super !== null && _super.apply(this, arguments) || this;
  83528. }
  83529. /**
  83530. * Gets a string describing the action executed by the current optimization
  83531. * @return description string
  83532. */
  83533. RenderTargetsOptimization.prototype.getDescription = function () {
  83534. return "Turning render targets off";
  83535. };
  83536. /**
  83537. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83538. * @param scene defines the current scene where to apply this optimization
  83539. * @param optimizer defines the current optimizer
  83540. * @returns true if everything that can be done was applied
  83541. */
  83542. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83543. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83544. return true;
  83545. };
  83546. ;
  83547. return RenderTargetsOptimization;
  83548. }(SceneOptimization));
  83549. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83550. /**
  83551. * Defines an optimization used to merge meshes with compatible materials
  83552. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83553. */
  83554. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83555. __extends(MergeMeshesOptimization, _super);
  83556. function MergeMeshesOptimization() {
  83557. var _this = _super !== null && _super.apply(this, arguments) || this;
  83558. _this._canBeMerged = function (abstractMesh) {
  83559. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83560. return false;
  83561. }
  83562. var mesh = abstractMesh;
  83563. if (!mesh.isVisible || !mesh.isEnabled()) {
  83564. return false;
  83565. }
  83566. if (mesh.instances.length > 0) {
  83567. return false;
  83568. }
  83569. if (mesh.skeleton || mesh.hasLODLevels) {
  83570. return false;
  83571. }
  83572. if (mesh.parent) {
  83573. return false;
  83574. }
  83575. return true;
  83576. };
  83577. return _this;
  83578. }
  83579. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83580. /**
  83581. * Gets or sets a boolean which defines if optimization octree has to be updated
  83582. */
  83583. get: function () {
  83584. return MergeMeshesOptimization._UpdateSelectionTree;
  83585. },
  83586. /**
  83587. * Gets or sets a boolean which defines if optimization octree has to be updated
  83588. */
  83589. set: function (value) {
  83590. MergeMeshesOptimization._UpdateSelectionTree = value;
  83591. },
  83592. enumerable: true,
  83593. configurable: true
  83594. });
  83595. /**
  83596. * Gets a string describing the action executed by the current optimization
  83597. * @return description string
  83598. */
  83599. MergeMeshesOptimization.prototype.getDescription = function () {
  83600. return "Merging similar meshes together";
  83601. };
  83602. /**
  83603. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83604. * @param scene defines the current scene where to apply this optimization
  83605. * @param optimizer defines the current optimizer
  83606. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83607. * @returns true if everything that can be done was applied
  83608. */
  83609. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83610. var globalPool = scene.meshes.slice(0);
  83611. var globalLength = globalPool.length;
  83612. for (var index = 0; index < globalLength; index++) {
  83613. var currentPool = new Array();
  83614. var current = globalPool[index];
  83615. // Checks
  83616. if (!this._canBeMerged(current)) {
  83617. continue;
  83618. }
  83619. currentPool.push(current);
  83620. // Find compatible meshes
  83621. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83622. var otherMesh = globalPool[subIndex];
  83623. if (!this._canBeMerged(otherMesh)) {
  83624. continue;
  83625. }
  83626. if (otherMesh.material !== current.material) {
  83627. continue;
  83628. }
  83629. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83630. continue;
  83631. }
  83632. currentPool.push(otherMesh);
  83633. globalLength--;
  83634. globalPool.splice(subIndex, 1);
  83635. subIndex--;
  83636. }
  83637. if (currentPool.length < 2) {
  83638. continue;
  83639. }
  83640. // Merge meshes
  83641. BABYLON.Mesh.MergeMeshes(currentPool);
  83642. }
  83643. if (updateSelectionTree != undefined) {
  83644. if (updateSelectionTree) {
  83645. scene.createOrUpdateSelectionOctree();
  83646. }
  83647. }
  83648. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83649. scene.createOrUpdateSelectionOctree();
  83650. }
  83651. return true;
  83652. };
  83653. ;
  83654. MergeMeshesOptimization._UpdateSelectionTree = false;
  83655. return MergeMeshesOptimization;
  83656. }(SceneOptimization));
  83657. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83658. /**
  83659. * Defines a list of options used by SceneOptimizer
  83660. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83661. */
  83662. var SceneOptimizerOptions = /** @class */ (function () {
  83663. /**
  83664. * Creates a new list of options used by SceneOptimizer
  83665. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83666. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83667. */
  83668. function SceneOptimizerOptions(
  83669. /**
  83670. * Defines the target frame rate to reach (60 by default)
  83671. */
  83672. targetFrameRate,
  83673. /**
  83674. * Defines the interval between two checkes (2000ms by default)
  83675. */
  83676. trackerDuration) {
  83677. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83678. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83679. this.targetFrameRate = targetFrameRate;
  83680. this.trackerDuration = trackerDuration;
  83681. /**
  83682. * Gets the list of optimizations to apply
  83683. */
  83684. this.optimizations = new Array();
  83685. }
  83686. /**
  83687. * Add a new optimization
  83688. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83689. * @returns the current SceneOptimizerOptions
  83690. */
  83691. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83692. this.optimizations.push(optimization);
  83693. return this;
  83694. };
  83695. /**
  83696. * Add a new custom optimization
  83697. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83698. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83699. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83700. * @returns the current SceneOptimizerOptions
  83701. */
  83702. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83703. if (priority === void 0) { priority = 0; }
  83704. var optimization = new CustomOptimization(priority);
  83705. optimization.onApply = onApply;
  83706. optimization.onGetDescription = onGetDescription;
  83707. this.optimizations.push(optimization);
  83708. return this;
  83709. };
  83710. /**
  83711. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83712. * @param targetFrameRate defines the target frame rate (60 by default)
  83713. * @returns a SceneOptimizerOptions object
  83714. */
  83715. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83716. var result = new SceneOptimizerOptions(targetFrameRate);
  83717. var priority = 0;
  83718. result.addOptimization(new MergeMeshesOptimization(priority));
  83719. result.addOptimization(new ShadowsOptimization(priority));
  83720. result.addOptimization(new LensFlaresOptimization(priority));
  83721. // Next priority
  83722. priority++;
  83723. result.addOptimization(new PostProcessesOptimization(priority));
  83724. result.addOptimization(new ParticlesOptimization(priority));
  83725. // Next priority
  83726. priority++;
  83727. result.addOptimization(new TextureOptimization(priority, 1024));
  83728. return result;
  83729. };
  83730. /**
  83731. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83732. * @param targetFrameRate defines the target frame rate (60 by default)
  83733. * @returns a SceneOptimizerOptions object
  83734. */
  83735. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83736. var result = new SceneOptimizerOptions(targetFrameRate);
  83737. var priority = 0;
  83738. result.addOptimization(new MergeMeshesOptimization(priority));
  83739. result.addOptimization(new ShadowsOptimization(priority));
  83740. result.addOptimization(new LensFlaresOptimization(priority));
  83741. // Next priority
  83742. priority++;
  83743. result.addOptimization(new PostProcessesOptimization(priority));
  83744. result.addOptimization(new ParticlesOptimization(priority));
  83745. // Next priority
  83746. priority++;
  83747. result.addOptimization(new TextureOptimization(priority, 512));
  83748. // Next priority
  83749. priority++;
  83750. result.addOptimization(new RenderTargetsOptimization(priority));
  83751. // Next priority
  83752. priority++;
  83753. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83754. return result;
  83755. };
  83756. /**
  83757. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83758. * @param targetFrameRate defines the target frame rate (60 by default)
  83759. * @returns a SceneOptimizerOptions object
  83760. */
  83761. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83762. var result = new SceneOptimizerOptions(targetFrameRate);
  83763. var priority = 0;
  83764. result.addOptimization(new MergeMeshesOptimization(priority));
  83765. result.addOptimization(new ShadowsOptimization(priority));
  83766. result.addOptimization(new LensFlaresOptimization(priority));
  83767. // Next priority
  83768. priority++;
  83769. result.addOptimization(new PostProcessesOptimization(priority));
  83770. result.addOptimization(new ParticlesOptimization(priority));
  83771. // Next priority
  83772. priority++;
  83773. result.addOptimization(new TextureOptimization(priority, 256));
  83774. // Next priority
  83775. priority++;
  83776. result.addOptimization(new RenderTargetsOptimization(priority));
  83777. // Next priority
  83778. priority++;
  83779. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83780. return result;
  83781. };
  83782. return SceneOptimizerOptions;
  83783. }());
  83784. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83785. /**
  83786. * Class used to run optimizations in order to reach a target frame rate
  83787. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83788. */
  83789. var SceneOptimizer = /** @class */ (function () {
  83790. /**
  83791. * Creates a new SceneOptimizer
  83792. * @param scene defines the scene to work on
  83793. * @param options defines the options to use with the SceneOptimizer
  83794. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83795. * @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)
  83796. */
  83797. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83798. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83799. if (improvementMode === void 0) { improvementMode = false; }
  83800. var _this = this;
  83801. this._isRunning = false;
  83802. this._currentPriorityLevel = 0;
  83803. this._targetFrameRate = 60;
  83804. this._trackerDuration = 2000;
  83805. this._currentFrameRate = 0;
  83806. this._improvementMode = false;
  83807. /**
  83808. * Defines an observable called when the optimizer reaches the target frame rate
  83809. */
  83810. this.onSuccessObservable = new BABYLON.Observable();
  83811. /**
  83812. * Defines an observable called when the optimizer enables an optimization
  83813. */
  83814. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83815. /**
  83816. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83817. */
  83818. this.onFailureObservable = new BABYLON.Observable();
  83819. if (!options) {
  83820. this._options = new SceneOptimizerOptions();
  83821. }
  83822. else {
  83823. this._options = options;
  83824. }
  83825. if (this._options.targetFrameRate) {
  83826. this._targetFrameRate = this._options.targetFrameRate;
  83827. }
  83828. if (this._options.trackerDuration) {
  83829. this._trackerDuration = this._options.trackerDuration;
  83830. }
  83831. if (autoGeneratePriorities) {
  83832. var priority = 0;
  83833. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83834. var optim = _a[_i];
  83835. optim.priority = priority++;
  83836. }
  83837. }
  83838. this._improvementMode = improvementMode;
  83839. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83840. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83841. _this._sceneDisposeObserver = null;
  83842. _this.dispose();
  83843. });
  83844. }
  83845. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83846. /**
  83847. * Gets a boolean indicating if the optimizer is in improvement mode
  83848. */
  83849. get: function () {
  83850. return this._improvementMode;
  83851. },
  83852. enumerable: true,
  83853. configurable: true
  83854. });
  83855. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83856. /**
  83857. * Gets the current priority level (0 at start)
  83858. */
  83859. get: function () {
  83860. return this._currentPriorityLevel;
  83861. },
  83862. enumerable: true,
  83863. configurable: true
  83864. });
  83865. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83866. /**
  83867. * Gets the current frame rate checked by the SceneOptimizer
  83868. */
  83869. get: function () {
  83870. return this._currentFrameRate;
  83871. },
  83872. enumerable: true,
  83873. configurable: true
  83874. });
  83875. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83876. /**
  83877. * Gets or sets the current target frame rate (60 by default)
  83878. */
  83879. get: function () {
  83880. return this._targetFrameRate;
  83881. },
  83882. /**
  83883. * Gets or sets the current target frame rate (60 by default)
  83884. */
  83885. set: function (value) {
  83886. this._targetFrameRate = value;
  83887. },
  83888. enumerable: true,
  83889. configurable: true
  83890. });
  83891. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83892. /**
  83893. * Gets or sets the current interval between two checks (every 2000ms by default)
  83894. */
  83895. get: function () {
  83896. return this._trackerDuration;
  83897. },
  83898. /**
  83899. * Gets or sets the current interval between two checks (every 2000ms by default)
  83900. */
  83901. set: function (value) {
  83902. this._trackerDuration = value;
  83903. },
  83904. enumerable: true,
  83905. configurable: true
  83906. });
  83907. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83908. /**
  83909. * Gets the list of active optimizations
  83910. */
  83911. get: function () {
  83912. return this._options.optimizations;
  83913. },
  83914. enumerable: true,
  83915. configurable: true
  83916. });
  83917. /**
  83918. * Stops the current optimizer
  83919. */
  83920. SceneOptimizer.prototype.stop = function () {
  83921. this._isRunning = false;
  83922. };
  83923. /**
  83924. * Reset the optimizer to initial step (current priority level = 0)
  83925. */
  83926. SceneOptimizer.prototype.reset = function () {
  83927. this._currentPriorityLevel = 0;
  83928. };
  83929. /**
  83930. * Start the optimizer. By default it will try to reach a specific framerate
  83931. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83932. */
  83933. SceneOptimizer.prototype.start = function () {
  83934. var _this = this;
  83935. if (this._isRunning) {
  83936. return;
  83937. }
  83938. this._isRunning = true;
  83939. // Let's wait for the scene to be ready before running our check
  83940. this._scene.executeWhenReady(function () {
  83941. setTimeout(function () {
  83942. _this._checkCurrentState();
  83943. }, _this._trackerDuration);
  83944. });
  83945. };
  83946. SceneOptimizer.prototype._checkCurrentState = function () {
  83947. var _this = this;
  83948. if (!this._isRunning) {
  83949. return;
  83950. }
  83951. var scene = this._scene;
  83952. var options = this._options;
  83953. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83954. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83955. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83956. this._isRunning = false;
  83957. this.onSuccessObservable.notifyObservers(this);
  83958. return;
  83959. }
  83960. // Apply current level of optimizations
  83961. var allDone = true;
  83962. var noOptimizationApplied = true;
  83963. for (var index = 0; index < options.optimizations.length; index++) {
  83964. var optimization = options.optimizations[index];
  83965. if (optimization.priority === this._currentPriorityLevel) {
  83966. noOptimizationApplied = false;
  83967. allDone = allDone && optimization.apply(scene, this);
  83968. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83969. }
  83970. }
  83971. // If no optimization was applied, this is a failure :(
  83972. if (noOptimizationApplied) {
  83973. this._isRunning = false;
  83974. this.onFailureObservable.notifyObservers(this);
  83975. return;
  83976. }
  83977. // If all optimizations were done, move to next level
  83978. if (allDone) {
  83979. this._currentPriorityLevel++;
  83980. }
  83981. // Let's the system running for a specific amount of time before checking FPS
  83982. scene.executeWhenReady(function () {
  83983. setTimeout(function () {
  83984. _this._checkCurrentState();
  83985. }, _this._trackerDuration);
  83986. });
  83987. };
  83988. /**
  83989. * Release all resources
  83990. */
  83991. SceneOptimizer.prototype.dispose = function () {
  83992. this.stop();
  83993. this.onSuccessObservable.clear();
  83994. this.onFailureObservable.clear();
  83995. this.onNewOptimizationAppliedObservable.clear();
  83996. if (this._sceneDisposeObserver) {
  83997. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83998. }
  83999. };
  84000. /**
  84001. * Helper function to create a SceneOptimizer with one single line of code
  84002. * @param scene defines the scene to work on
  84003. * @param options defines the options to use with the SceneOptimizer
  84004. * @param onSuccess defines a callback to call on success
  84005. * @param onFailure defines a callback to call on failure
  84006. * @returns the new SceneOptimizer object
  84007. */
  84008. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84009. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84010. if (onSuccess) {
  84011. optimizer.onSuccessObservable.add(function () {
  84012. onSuccess();
  84013. });
  84014. }
  84015. if (onFailure) {
  84016. optimizer.onFailureObservable.add(function () {
  84017. onFailure();
  84018. });
  84019. }
  84020. optimizer.start();
  84021. return optimizer;
  84022. };
  84023. return SceneOptimizer;
  84024. }());
  84025. BABYLON.SceneOptimizer = SceneOptimizer;
  84026. })(BABYLON || (BABYLON = {}));
  84027. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84028. var BABYLON;
  84029. (function (BABYLON) {
  84030. var OutlineRenderer = /** @class */ (function () {
  84031. function OutlineRenderer(scene) {
  84032. this.zOffset = 1;
  84033. this._scene = scene;
  84034. }
  84035. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84036. var _this = this;
  84037. if (useOverlay === void 0) { useOverlay = false; }
  84038. var scene = this._scene;
  84039. var engine = this._scene.getEngine();
  84040. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84041. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84042. return;
  84043. }
  84044. var mesh = subMesh.getRenderingMesh();
  84045. var material = subMesh.getMaterial();
  84046. if (!material || !scene.activeCamera) {
  84047. return;
  84048. }
  84049. engine.enableEffect(this._effect);
  84050. // Logarithmic depth
  84051. if (material.useLogarithmicDepth) {
  84052. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84053. }
  84054. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84055. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84056. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84057. // Bones
  84058. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84059. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84060. }
  84061. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84062. // Alpha test
  84063. if (material && material.needAlphaTesting()) {
  84064. var alphaTexture = material.getAlphaTestTexture();
  84065. if (alphaTexture) {
  84066. this._effect.setTexture("diffuseSampler", alphaTexture);
  84067. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84068. }
  84069. }
  84070. engine.setZOffset(-this.zOffset);
  84071. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84072. engine.setZOffset(0);
  84073. };
  84074. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84075. var defines = [];
  84076. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84077. var mesh = subMesh.getMesh();
  84078. var material = subMesh.getMaterial();
  84079. if (material) {
  84080. // Alpha test
  84081. if (material.needAlphaTesting()) {
  84082. defines.push("#define ALPHATEST");
  84083. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84084. attribs.push(BABYLON.VertexBuffer.UVKind);
  84085. defines.push("#define UV1");
  84086. }
  84087. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84088. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84089. defines.push("#define UV2");
  84090. }
  84091. }
  84092. //Logarithmic depth
  84093. if (material.useLogarithmicDepth) {
  84094. defines.push("#define LOGARITHMICDEPTH");
  84095. }
  84096. }
  84097. // Bones
  84098. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84099. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84100. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84101. if (mesh.numBoneInfluencers > 4) {
  84102. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84103. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84104. }
  84105. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84106. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84107. }
  84108. else {
  84109. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84110. }
  84111. // Instances
  84112. if (useInstances) {
  84113. defines.push("#define INSTANCES");
  84114. attribs.push("world0");
  84115. attribs.push("world1");
  84116. attribs.push("world2");
  84117. attribs.push("world3");
  84118. }
  84119. // Get correct effect
  84120. var join = defines.join("\n");
  84121. if (this._cachedDefines !== join) {
  84122. this._cachedDefines = join;
  84123. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84124. }
  84125. return this._effect.isReady();
  84126. };
  84127. return OutlineRenderer;
  84128. }());
  84129. BABYLON.OutlineRenderer = OutlineRenderer;
  84130. })(BABYLON || (BABYLON = {}));
  84131. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84132. var BABYLON;
  84133. (function (BABYLON) {
  84134. var FaceAdjacencies = /** @class */ (function () {
  84135. function FaceAdjacencies() {
  84136. this.edges = new Array();
  84137. this.edgesConnectedCount = 0;
  84138. }
  84139. return FaceAdjacencies;
  84140. }());
  84141. var EdgesRenderer = /** @class */ (function () {
  84142. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84143. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84144. if (epsilon === void 0) { epsilon = 0.95; }
  84145. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84146. this.edgesWidthScalerForOrthographic = 1000.0;
  84147. this.edgesWidthScalerForPerspective = 50.0;
  84148. this._linesPositions = new Array();
  84149. this._linesNormals = new Array();
  84150. this._linesIndices = new Array();
  84151. this._buffers = {};
  84152. this._checkVerticesInsteadOfIndices = false;
  84153. this._source = source;
  84154. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84155. this._epsilon = epsilon;
  84156. this._prepareRessources();
  84157. this._generateEdgesLines();
  84158. }
  84159. EdgesRenderer.prototype._prepareRessources = function () {
  84160. if (this._lineShader) {
  84161. return;
  84162. }
  84163. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84164. attributes: ["position", "normal"],
  84165. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84166. });
  84167. this._lineShader.disableDepthWrite = true;
  84168. this._lineShader.backFaceCulling = false;
  84169. };
  84170. EdgesRenderer.prototype._rebuild = function () {
  84171. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84172. if (buffer) {
  84173. buffer._rebuild();
  84174. }
  84175. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84176. if (buffer) {
  84177. buffer._rebuild();
  84178. }
  84179. var scene = this._source.getScene();
  84180. var engine = scene.getEngine();
  84181. this._ib = engine.createIndexBuffer(this._linesIndices);
  84182. };
  84183. EdgesRenderer.prototype.dispose = function () {
  84184. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84185. if (buffer) {
  84186. buffer.dispose();
  84187. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84188. }
  84189. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84190. if (buffer) {
  84191. buffer.dispose();
  84192. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84193. }
  84194. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84195. this._lineShader.dispose();
  84196. };
  84197. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84198. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84199. return 0;
  84200. }
  84201. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84202. return 1;
  84203. }
  84204. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84205. return 2;
  84206. }
  84207. return -1;
  84208. };
  84209. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84210. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84211. return 0;
  84212. }
  84213. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84214. return 1;
  84215. }
  84216. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84217. return 2;
  84218. }
  84219. return -1;
  84220. };
  84221. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84222. var needToCreateLine;
  84223. if (edge === undefined) {
  84224. needToCreateLine = true;
  84225. }
  84226. else {
  84227. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84228. needToCreateLine = dotProduct < this._epsilon;
  84229. }
  84230. if (needToCreateLine) {
  84231. var offset = this._linesPositions.length / 3;
  84232. var normal = p0.subtract(p1);
  84233. normal.normalize();
  84234. // Positions
  84235. this._linesPositions.push(p0.x);
  84236. this._linesPositions.push(p0.y);
  84237. this._linesPositions.push(p0.z);
  84238. this._linesPositions.push(p0.x);
  84239. this._linesPositions.push(p0.y);
  84240. this._linesPositions.push(p0.z);
  84241. this._linesPositions.push(p1.x);
  84242. this._linesPositions.push(p1.y);
  84243. this._linesPositions.push(p1.z);
  84244. this._linesPositions.push(p1.x);
  84245. this._linesPositions.push(p1.y);
  84246. this._linesPositions.push(p1.z);
  84247. // Normals
  84248. this._linesNormals.push(p1.x);
  84249. this._linesNormals.push(p1.y);
  84250. this._linesNormals.push(p1.z);
  84251. this._linesNormals.push(-1);
  84252. this._linesNormals.push(p1.x);
  84253. this._linesNormals.push(p1.y);
  84254. this._linesNormals.push(p1.z);
  84255. this._linesNormals.push(1);
  84256. this._linesNormals.push(p0.x);
  84257. this._linesNormals.push(p0.y);
  84258. this._linesNormals.push(p0.z);
  84259. this._linesNormals.push(-1);
  84260. this._linesNormals.push(p0.x);
  84261. this._linesNormals.push(p0.y);
  84262. this._linesNormals.push(p0.z);
  84263. this._linesNormals.push(1);
  84264. // Indices
  84265. this._linesIndices.push(offset);
  84266. this._linesIndices.push(offset + 1);
  84267. this._linesIndices.push(offset + 2);
  84268. this._linesIndices.push(offset);
  84269. this._linesIndices.push(offset + 2);
  84270. this._linesIndices.push(offset + 3);
  84271. }
  84272. };
  84273. EdgesRenderer.prototype._generateEdgesLines = function () {
  84274. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84275. var indices = this._source.getIndices();
  84276. if (!indices || !positions) {
  84277. return;
  84278. }
  84279. // First let's find adjacencies
  84280. var adjacencies = new Array();
  84281. var faceNormals = new Array();
  84282. var index;
  84283. var faceAdjacencies;
  84284. // Prepare faces
  84285. for (index = 0; index < indices.length; index += 3) {
  84286. faceAdjacencies = new FaceAdjacencies();
  84287. var p0Index = indices[index];
  84288. var p1Index = indices[index + 1];
  84289. var p2Index = indices[index + 2];
  84290. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84291. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84292. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84293. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84294. faceNormal.normalize();
  84295. faceNormals.push(faceNormal);
  84296. adjacencies.push(faceAdjacencies);
  84297. }
  84298. // Scan
  84299. for (index = 0; index < adjacencies.length; index++) {
  84300. faceAdjacencies = adjacencies[index];
  84301. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84302. var otherFaceAdjacencies = adjacencies[otherIndex];
  84303. if (faceAdjacencies.edgesConnectedCount === 3) {
  84304. break;
  84305. }
  84306. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84307. continue;
  84308. }
  84309. var otherP0 = indices[otherIndex * 3];
  84310. var otherP1 = indices[otherIndex * 3 + 1];
  84311. var otherP2 = indices[otherIndex * 3 + 2];
  84312. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84313. var otherEdgeIndex = 0;
  84314. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84315. continue;
  84316. }
  84317. switch (edgeIndex) {
  84318. case 0:
  84319. if (this._checkVerticesInsteadOfIndices) {
  84320. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84321. }
  84322. else {
  84323. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84324. }
  84325. break;
  84326. case 1:
  84327. if (this._checkVerticesInsteadOfIndices) {
  84328. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84329. }
  84330. else {
  84331. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84332. }
  84333. break;
  84334. case 2:
  84335. if (this._checkVerticesInsteadOfIndices) {
  84336. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84337. }
  84338. else {
  84339. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84340. }
  84341. break;
  84342. }
  84343. if (otherEdgeIndex === -1) {
  84344. continue;
  84345. }
  84346. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84347. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84348. faceAdjacencies.edgesConnectedCount++;
  84349. otherFaceAdjacencies.edgesConnectedCount++;
  84350. if (faceAdjacencies.edgesConnectedCount === 3) {
  84351. break;
  84352. }
  84353. }
  84354. }
  84355. }
  84356. // Create lines
  84357. for (index = 0; index < adjacencies.length; index++) {
  84358. // 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
  84359. var current = adjacencies[index];
  84360. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84361. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84362. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84363. }
  84364. // Merge into a single mesh
  84365. var engine = this._source.getScene().getEngine();
  84366. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84367. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84368. this._ib = engine.createIndexBuffer(this._linesIndices);
  84369. this._indicesCount = this._linesIndices.length;
  84370. };
  84371. EdgesRenderer.prototype.render = function () {
  84372. var scene = this._source.getScene();
  84373. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84374. return;
  84375. }
  84376. var engine = scene.getEngine();
  84377. this._lineShader._preBind();
  84378. // VBOs
  84379. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84380. scene.resetCachedMaterial();
  84381. this._lineShader.setColor4("color", this._source.edgesColor);
  84382. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84383. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84384. }
  84385. else {
  84386. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84387. }
  84388. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84389. this._lineShader.bind(this._source.getWorldMatrix());
  84390. // Draw order
  84391. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84392. this._lineShader.unbind();
  84393. engine.setDepthWrite(true);
  84394. };
  84395. return EdgesRenderer;
  84396. }());
  84397. BABYLON.EdgesRenderer = EdgesRenderer;
  84398. })(BABYLON || (BABYLON = {}));
  84399. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84400. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84401. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84402. s = arguments[i];
  84403. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84404. t[p] = s[p];
  84405. }
  84406. return t;
  84407. };
  84408. var BABYLON;
  84409. (function (BABYLON) {
  84410. /**
  84411. * The effect layer Helps adding post process effect blended with the main pass.
  84412. *
  84413. * This can be for instance use to generate glow or higlight effects on the scene.
  84414. *
  84415. * The effect layer class can not be used directly and is intented to inherited from to be
  84416. * customized per effects.
  84417. */
  84418. var EffectLayer = /** @class */ (function () {
  84419. /**
  84420. * Instantiates a new effect Layer and references it in the scene.
  84421. * @param name The name of the layer
  84422. * @param scene The scene to use the layer in
  84423. */
  84424. function EffectLayer(
  84425. /** The Friendly of the effect in the scene */
  84426. name, scene) {
  84427. this.name = name;
  84428. this._vertexBuffers = {};
  84429. this._maxSize = 0;
  84430. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84431. this._shouldRender = true;
  84432. this._postProcesses = [];
  84433. this._textures = [];
  84434. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84435. /**
  84436. * The clear color of the texture used to generate the glow map.
  84437. */
  84438. this.neutralColor = new BABYLON.Color4();
  84439. /**
  84440. * Specifies wether the highlight layer is enabled or not.
  84441. */
  84442. this.isEnabled = true;
  84443. /**
  84444. * An event triggered when the effect layer has been disposed.
  84445. */
  84446. this.onDisposeObservable = new BABYLON.Observable();
  84447. /**
  84448. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84449. */
  84450. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84451. /**
  84452. * An event triggered when the generated texture is being merged in the scene.
  84453. */
  84454. this.onBeforeComposeObservable = new BABYLON.Observable();
  84455. /**
  84456. * An event triggered when the generated texture has been merged in the scene.
  84457. */
  84458. this.onAfterComposeObservable = new BABYLON.Observable();
  84459. /**
  84460. * An event triggered when the efffect layer changes its size.
  84461. */
  84462. this.onSizeChangedObservable = new BABYLON.Observable();
  84463. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84464. this._engine = scene.getEngine();
  84465. this._maxSize = this._engine.getCaps().maxTextureSize;
  84466. this._scene.effectLayers.push(this);
  84467. // Generate Buffers
  84468. this._generateIndexBuffer();
  84469. this._genrateVertexBuffer();
  84470. }
  84471. Object.defineProperty(EffectLayer.prototype, "camera", {
  84472. /**
  84473. * Gets the camera attached to the layer.
  84474. */
  84475. get: function () {
  84476. return this._effectLayerOptions.camera;
  84477. },
  84478. enumerable: true,
  84479. configurable: true
  84480. });
  84481. /**
  84482. * Initializes the effect layer with the required options.
  84483. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84484. */
  84485. EffectLayer.prototype._init = function (options) {
  84486. // Adapt options
  84487. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84488. this._setMainTextureSize();
  84489. this._createMainTexture();
  84490. this._createTextureAndPostProcesses();
  84491. this._mergeEffect = this._createMergeEffect();
  84492. };
  84493. /**
  84494. * Generates the index buffer of the full screen quad blending to the main canvas.
  84495. */
  84496. EffectLayer.prototype._generateIndexBuffer = function () {
  84497. // Indices
  84498. var indices = [];
  84499. indices.push(0);
  84500. indices.push(1);
  84501. indices.push(2);
  84502. indices.push(0);
  84503. indices.push(2);
  84504. indices.push(3);
  84505. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84506. };
  84507. /**
  84508. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84509. */
  84510. EffectLayer.prototype._genrateVertexBuffer = function () {
  84511. // VBO
  84512. var vertices = [];
  84513. vertices.push(1, 1);
  84514. vertices.push(-1, 1);
  84515. vertices.push(-1, -1);
  84516. vertices.push(1, -1);
  84517. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84518. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84519. };
  84520. /**
  84521. * Sets the main texture desired size which is the closest power of two
  84522. * of the engine canvas size.
  84523. */
  84524. EffectLayer.prototype._setMainTextureSize = function () {
  84525. if (this._effectLayerOptions.mainTextureFixedSize) {
  84526. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84527. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84528. }
  84529. else {
  84530. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84531. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84532. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84533. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84534. }
  84535. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84536. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84537. };
  84538. /**
  84539. * Creates the main texture for the effect layer.
  84540. */
  84541. EffectLayer.prototype._createMainTexture = function () {
  84542. var _this = this;
  84543. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84544. width: this._mainTextureDesiredSize.width,
  84545. height: this._mainTextureDesiredSize.height
  84546. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84547. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84548. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84549. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84550. this._mainTexture.anisotropicFilteringLevel = 1;
  84551. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84552. this._mainTexture.renderParticles = false;
  84553. this._mainTexture.renderList = null;
  84554. this._mainTexture.ignoreCameraViewport = true;
  84555. // Custom render function
  84556. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84557. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84558. var index;
  84559. var engine = _this._scene.getEngine();
  84560. if (depthOnlySubMeshes.length) {
  84561. engine.setColorWrite(false);
  84562. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84563. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84564. }
  84565. engine.setColorWrite(true);
  84566. }
  84567. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84568. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84569. }
  84570. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84571. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84572. }
  84573. for (index = 0; index < transparentSubMeshes.length; index++) {
  84574. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84575. }
  84576. };
  84577. this._mainTexture.onClearObservable.add(function (engine) {
  84578. engine.clear(_this.neutralColor, true, true, true);
  84579. });
  84580. };
  84581. /**
  84582. * Checks for the readiness of the element composing the layer.
  84583. * @param subMesh the mesh to check for
  84584. * @param useInstances specify wether or not to use instances to render the mesh
  84585. * @param emissiveTexture the associated emissive texture used to generate the glow
  84586. * @return true if ready otherwise, false
  84587. */
  84588. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84589. var material = subMesh.getMaterial();
  84590. if (!material) {
  84591. return false;
  84592. }
  84593. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84594. return false;
  84595. }
  84596. var defines = [];
  84597. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84598. var mesh = subMesh.getMesh();
  84599. var uv1 = false;
  84600. var uv2 = false;
  84601. // Alpha test
  84602. if (material && material.needAlphaTesting()) {
  84603. var alphaTexture = material.getAlphaTestTexture();
  84604. if (alphaTexture) {
  84605. defines.push("#define ALPHATEST");
  84606. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84607. alphaTexture.coordinatesIndex === 1) {
  84608. defines.push("#define DIFFUSEUV2");
  84609. uv2 = true;
  84610. }
  84611. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84612. defines.push("#define DIFFUSEUV1");
  84613. uv1 = true;
  84614. }
  84615. }
  84616. }
  84617. // Emissive
  84618. if (emissiveTexture) {
  84619. defines.push("#define EMISSIVE");
  84620. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84621. emissiveTexture.coordinatesIndex === 1) {
  84622. defines.push("#define EMISSIVEUV2");
  84623. uv2 = true;
  84624. }
  84625. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84626. defines.push("#define EMISSIVEUV1");
  84627. uv1 = true;
  84628. }
  84629. }
  84630. if (uv1) {
  84631. attribs.push(BABYLON.VertexBuffer.UVKind);
  84632. defines.push("#define UV1");
  84633. }
  84634. if (uv2) {
  84635. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84636. defines.push("#define UV2");
  84637. }
  84638. // Bones
  84639. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84640. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84641. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84642. if (mesh.numBoneInfluencers > 4) {
  84643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84645. }
  84646. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84647. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84648. }
  84649. else {
  84650. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84651. }
  84652. // Instances
  84653. if (useInstances) {
  84654. defines.push("#define INSTANCES");
  84655. attribs.push("world0");
  84656. attribs.push("world1");
  84657. attribs.push("world2");
  84658. attribs.push("world3");
  84659. }
  84660. // Get correct effect
  84661. var join = defines.join("\n");
  84662. if (this._cachedDefines !== join) {
  84663. this._cachedDefines = join;
  84664. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84665. }
  84666. return this._effectLayerMapGenerationEffect.isReady();
  84667. };
  84668. /**
  84669. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84670. */
  84671. EffectLayer.prototype.render = function () {
  84672. var currentEffect = this._mergeEffect;
  84673. // Check
  84674. if (!currentEffect.isReady())
  84675. return;
  84676. for (var i = 0; i < this._postProcesses.length; i++) {
  84677. if (!this._postProcesses[i].isReady()) {
  84678. return;
  84679. }
  84680. }
  84681. var engine = this._scene.getEngine();
  84682. this.onBeforeComposeObservable.notifyObservers(this);
  84683. // Render
  84684. engine.enableEffect(currentEffect);
  84685. engine.setState(false);
  84686. // VBOs
  84687. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84688. // Cache
  84689. var previousAlphaMode = engine.getAlphaMode();
  84690. // Go Blend.
  84691. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84692. // Blends the map on the main canvas.
  84693. this._internalRender(currentEffect);
  84694. // Restore Alpha
  84695. engine.setAlphaMode(previousAlphaMode);
  84696. this.onAfterComposeObservable.notifyObservers(this);
  84697. // Handle size changes.
  84698. var size = this._mainTexture.getSize();
  84699. this._setMainTextureSize();
  84700. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84701. // Recreate RTT and post processes on size change.
  84702. this.onSizeChangedObservable.notifyObservers(this);
  84703. this._disposeTextureAndPostProcesses();
  84704. this._createMainTexture();
  84705. this._createTextureAndPostProcesses();
  84706. }
  84707. };
  84708. /**
  84709. * Determine if a given mesh will be used in the current effect.
  84710. * @param mesh mesh to test
  84711. * @returns true if the mesh will be used
  84712. */
  84713. EffectLayer.prototype.hasMesh = function (mesh) {
  84714. return true;
  84715. };
  84716. /**
  84717. * Returns true if the layer contains information to display, otherwise false.
  84718. * @returns true if the glow layer should be rendered
  84719. */
  84720. EffectLayer.prototype.shouldRender = function () {
  84721. return this.isEnabled && this._shouldRender;
  84722. };
  84723. /**
  84724. * Returns true if the mesh should render, otherwise false.
  84725. * @param mesh The mesh to render
  84726. * @returns true if it should render otherwise false
  84727. */
  84728. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84729. return true;
  84730. };
  84731. /**
  84732. * Returns true if the mesh should render, otherwise false.
  84733. * @param mesh The mesh to render
  84734. * @returns true if it should render otherwise false
  84735. */
  84736. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84737. return true;
  84738. };
  84739. /**
  84740. * Renders the submesh passed in parameter to the generation map.
  84741. */
  84742. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84743. var _this = this;
  84744. if (!this.shouldRender()) {
  84745. return;
  84746. }
  84747. var material = subMesh.getMaterial();
  84748. var mesh = subMesh.getRenderingMesh();
  84749. var scene = this._scene;
  84750. var engine = scene.getEngine();
  84751. if (!material) {
  84752. return;
  84753. }
  84754. // Do not block in blend mode.
  84755. if (material.needAlphaBlendingForMesh(mesh)) {
  84756. return;
  84757. }
  84758. // Culling
  84759. engine.setState(material.backFaceCulling);
  84760. // Managing instances
  84761. var batch = mesh._getInstancesRenderList(subMesh._id);
  84762. if (batch.mustReturn) {
  84763. return;
  84764. }
  84765. // Early Exit per mesh
  84766. if (!this._shouldRenderMesh(mesh)) {
  84767. return;
  84768. }
  84769. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84770. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84771. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84772. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84773. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84774. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84775. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84776. // Alpha test
  84777. if (material && material.needAlphaTesting()) {
  84778. var alphaTexture = material.getAlphaTestTexture();
  84779. if (alphaTexture) {
  84780. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84781. var textureMatrix = alphaTexture.getTextureMatrix();
  84782. if (textureMatrix) {
  84783. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84784. }
  84785. }
  84786. }
  84787. // Glow emissive only
  84788. if (this._emissiveTextureAndColor.texture) {
  84789. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84790. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84791. }
  84792. // Bones
  84793. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84794. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84795. }
  84796. // Draw
  84797. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84798. }
  84799. else {
  84800. // Need to reset refresh rate of the shadowMap
  84801. this._mainTexture.resetRefreshCounter();
  84802. }
  84803. };
  84804. /**
  84805. * Rebuild the required buffers.
  84806. * @ignore Internal use only.
  84807. */
  84808. EffectLayer.prototype._rebuild = function () {
  84809. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84810. if (vb) {
  84811. vb._rebuild();
  84812. }
  84813. this._generateIndexBuffer();
  84814. };
  84815. /**
  84816. * Dispose only the render target textures and post process.
  84817. */
  84818. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84819. this._mainTexture.dispose();
  84820. for (var i = 0; i < this._postProcesses.length; i++) {
  84821. if (this._postProcesses[i]) {
  84822. this._postProcesses[i].dispose();
  84823. }
  84824. }
  84825. this._postProcesses = [];
  84826. for (var i = 0; i < this._textures.length; i++) {
  84827. if (this._textures[i]) {
  84828. this._textures[i].dispose();
  84829. }
  84830. }
  84831. this._textures = [];
  84832. };
  84833. /**
  84834. * Dispose the highlight layer and free resources.
  84835. */
  84836. EffectLayer.prototype.dispose = function () {
  84837. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84838. if (vertexBuffer) {
  84839. vertexBuffer.dispose();
  84840. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84841. }
  84842. if (this._indexBuffer) {
  84843. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84844. this._indexBuffer = null;
  84845. }
  84846. // Clean textures and post processes
  84847. this._disposeTextureAndPostProcesses();
  84848. // Remove from scene
  84849. var index = this._scene.effectLayers.indexOf(this, 0);
  84850. if (index > -1) {
  84851. this._scene.effectLayers.splice(index, 1);
  84852. }
  84853. // Callback
  84854. this.onDisposeObservable.notifyObservers(this);
  84855. this.onDisposeObservable.clear();
  84856. this.onBeforeRenderMainTextureObservable.clear();
  84857. this.onBeforeComposeObservable.clear();
  84858. this.onAfterComposeObservable.clear();
  84859. this.onSizeChangedObservable.clear();
  84860. };
  84861. return EffectLayer;
  84862. }());
  84863. BABYLON.EffectLayer = EffectLayer;
  84864. })(BABYLON || (BABYLON = {}));
  84865. //# sourceMappingURL=babylon.effectLayer.js.map
  84866. var BABYLON;
  84867. (function (BABYLON) {
  84868. /**
  84869. * Special Glow Blur post process only blurring the alpha channel
  84870. * It enforces keeping the most luminous color in the color channel.
  84871. */
  84872. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84873. __extends(GlowBlurPostProcess, _super);
  84874. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84876. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84877. _this.direction = direction;
  84878. _this.kernel = kernel;
  84879. _this.onApplyObservable.add(function (effect) {
  84880. effect.setFloat2("screenSize", _this.width, _this.height);
  84881. effect.setVector2("direction", _this.direction);
  84882. effect.setFloat("blurWidth", _this.kernel);
  84883. });
  84884. return _this;
  84885. }
  84886. return GlowBlurPostProcess;
  84887. }(BABYLON.PostProcess));
  84888. /**
  84889. * The highlight layer Helps adding a glow effect around a mesh.
  84890. *
  84891. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84892. * glowy meshes to your scene.
  84893. *
  84894. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84895. */
  84896. var HighlightLayer = /** @class */ (function (_super) {
  84897. __extends(HighlightLayer, _super);
  84898. /**
  84899. * Instantiates a new highlight Layer and references it to the scene..
  84900. * @param name The name of the layer
  84901. * @param scene The scene to use the layer in
  84902. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84903. */
  84904. function HighlightLayer(name, scene, options) {
  84905. var _this = _super.call(this, name, scene) || this;
  84906. _this.name = name;
  84907. /**
  84908. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84909. */
  84910. _this.innerGlow = true;
  84911. /**
  84912. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84913. */
  84914. _this.outerGlow = true;
  84915. /**
  84916. * An event triggered when the highlight layer is being blurred.
  84917. */
  84918. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84919. /**
  84920. * An event triggered when the highlight layer has been blurred.
  84921. */
  84922. _this.onAfterBlurObservable = new BABYLON.Observable();
  84923. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84924. _this._meshes = {};
  84925. _this._excludedMeshes = {};
  84926. _this.neutralColor = HighlightLayer.NeutralColor;
  84927. // Warn on stencil
  84928. if (!_this._engine.isStencilEnable) {
  84929. 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 }");
  84930. }
  84931. // Adapt options
  84932. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84933. // Initialize the layer
  84934. _this._init({
  84935. alphaBlendingMode: _this._options.alphaBlendingMode,
  84936. camera: _this._options.camera,
  84937. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84938. mainTextureRatio: _this._options.mainTextureRatio
  84939. });
  84940. // Do not render as long as no meshes have been added
  84941. _this._shouldRender = false;
  84942. return _this;
  84943. }
  84944. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84945. /**
  84946. * Gets the horizontal size of the blur.
  84947. */
  84948. get: function () {
  84949. return this._horizontalBlurPostprocess.kernel;
  84950. },
  84951. /**
  84952. * Specifies the horizontal size of the blur.
  84953. */
  84954. set: function (value) {
  84955. this._horizontalBlurPostprocess.kernel = value;
  84956. },
  84957. enumerable: true,
  84958. configurable: true
  84959. });
  84960. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84961. /**
  84962. * Gets the vertical size of the blur.
  84963. */
  84964. get: function () {
  84965. return this._verticalBlurPostprocess.kernel;
  84966. },
  84967. /**
  84968. * Specifies the vertical size of the blur.
  84969. */
  84970. set: function (value) {
  84971. this._verticalBlurPostprocess.kernel = value;
  84972. },
  84973. enumerable: true,
  84974. configurable: true
  84975. });
  84976. /**
  84977. * Get the effect name of the layer.
  84978. * @return The effect name
  84979. */
  84980. HighlightLayer.prototype.getEffectName = function () {
  84981. return HighlightLayer.EffectName;
  84982. };
  84983. /**
  84984. * Create the merge effect. This is the shader use to blit the information back
  84985. * to the main canvas at the end of the scene rendering.
  84986. */
  84987. HighlightLayer.prototype._createMergeEffect = function () {
  84988. // Effect
  84989. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84990. };
  84991. /**
  84992. * Creates the render target textures and post processes used in the highlight layer.
  84993. */
  84994. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84995. var _this = this;
  84996. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84997. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84998. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84999. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85000. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85001. width: blurTextureWidth,
  85002. height: blurTextureHeight
  85003. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85004. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85005. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85006. this._blurTexture.anisotropicFilteringLevel = 16;
  85007. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85008. this._blurTexture.renderParticles = false;
  85009. this._blurTexture.ignoreCameraViewport = true;
  85010. this._textures = [this._blurTexture];
  85011. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85012. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85013. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85014. effect.setTexture("textureSampler", _this._mainTexture);
  85015. });
  85016. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85017. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85018. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85019. });
  85020. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85021. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85022. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85023. });
  85024. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85025. }
  85026. else {
  85027. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85028. width: blurTextureWidth,
  85029. height: blurTextureHeight
  85030. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85031. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85032. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85033. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85034. effect.setTexture("textureSampler", _this._mainTexture);
  85035. });
  85036. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85037. width: blurTextureWidth,
  85038. height: blurTextureHeight
  85039. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85040. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85041. }
  85042. this._mainTexture.onAfterUnbindObservable.add(function () {
  85043. _this.onBeforeBlurObservable.notifyObservers(_this);
  85044. var internalTexture = _this._blurTexture.getInternalTexture();
  85045. if (internalTexture) {
  85046. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85047. }
  85048. _this.onAfterBlurObservable.notifyObservers(_this);
  85049. });
  85050. // Prevent autoClear.
  85051. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85052. };
  85053. /**
  85054. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85055. */
  85056. HighlightLayer.prototype.needStencil = function () {
  85057. return true;
  85058. };
  85059. /**
  85060. * Checks for the readiness of the element composing the layer.
  85061. * @param subMesh the mesh to check for
  85062. * @param useInstances specify wether or not to use instances to render the mesh
  85063. * @param emissiveTexture the associated emissive texture used to generate the glow
  85064. * @return true if ready otherwise, false
  85065. */
  85066. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85067. var material = subMesh.getMaterial();
  85068. var mesh = subMesh.getRenderingMesh();
  85069. if (!material || !mesh || !this._meshes) {
  85070. return false;
  85071. }
  85072. var emissiveTexture = null;
  85073. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85074. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85075. emissiveTexture = material.emissiveTexture;
  85076. }
  85077. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85078. };
  85079. /**
  85080. * Implementation specific of rendering the generating effect on the main canvas.
  85081. * @param effect The effect used to render through
  85082. */
  85083. HighlightLayer.prototype._internalRender = function (effect) {
  85084. // Texture
  85085. effect.setTexture("textureSampler", this._blurTexture);
  85086. // Cache
  85087. var engine = this._engine;
  85088. var previousStencilBuffer = engine.getStencilBuffer();
  85089. var previousStencilFunction = engine.getStencilFunction();
  85090. var previousStencilMask = engine.getStencilMask();
  85091. var previousStencilOperationPass = engine.getStencilOperationPass();
  85092. var previousStencilOperationFail = engine.getStencilOperationFail();
  85093. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85094. var previousStencilReference = engine.getStencilFunctionReference();
  85095. // Stencil operations
  85096. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85097. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85098. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85099. // Draw order
  85100. engine.setStencilMask(0x00);
  85101. engine.setStencilBuffer(true);
  85102. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85103. // 2 passes inner outer
  85104. if (this.outerGlow) {
  85105. effect.setFloat("offset", 0);
  85106. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85107. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85108. }
  85109. if (this.innerGlow) {
  85110. effect.setFloat("offset", 1);
  85111. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85112. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85113. }
  85114. // Restore Cache
  85115. engine.setStencilFunction(previousStencilFunction);
  85116. engine.setStencilMask(previousStencilMask);
  85117. engine.setStencilBuffer(previousStencilBuffer);
  85118. engine.setStencilOperationPass(previousStencilOperationPass);
  85119. engine.setStencilOperationFail(previousStencilOperationFail);
  85120. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85121. engine.setStencilFunctionReference(previousStencilReference);
  85122. };
  85123. /**
  85124. * Returns true if the layer contains information to display, otherwise false.
  85125. */
  85126. HighlightLayer.prototype.shouldRender = function () {
  85127. if (_super.prototype.shouldRender.call(this)) {
  85128. return this._meshes ? true : false;
  85129. }
  85130. return false;
  85131. };
  85132. /**
  85133. * Returns true if the mesh should render, otherwise false.
  85134. * @param mesh The mesh to render
  85135. * @returns true if it should render otherwise false
  85136. */
  85137. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85138. // Excluded Mesh
  85139. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85140. return false;
  85141. }
  85142. ;
  85143. return true;
  85144. };
  85145. /**
  85146. * Sets the required values for both the emissive texture and and the main color.
  85147. */
  85148. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85149. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85150. if (highlightLayerMesh) {
  85151. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85152. }
  85153. else {
  85154. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85155. }
  85156. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85157. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85158. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85159. }
  85160. else {
  85161. this._emissiveTextureAndColor.texture = null;
  85162. }
  85163. };
  85164. /**
  85165. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85166. * @param mesh The mesh to exclude from the highlight layer
  85167. */
  85168. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85169. if (!this._excludedMeshes) {
  85170. return;
  85171. }
  85172. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85173. if (!meshExcluded) {
  85174. this._excludedMeshes[mesh.uniqueId] = {
  85175. mesh: mesh,
  85176. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85177. mesh.getEngine().setStencilBuffer(false);
  85178. }),
  85179. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85180. mesh.getEngine().setStencilBuffer(true);
  85181. }),
  85182. };
  85183. }
  85184. };
  85185. /**
  85186. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85187. * @param mesh The mesh to highlight
  85188. */
  85189. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85190. if (!this._excludedMeshes) {
  85191. return;
  85192. }
  85193. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85194. if (meshExcluded) {
  85195. if (meshExcluded.beforeRender) {
  85196. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85197. }
  85198. if (meshExcluded.afterRender) {
  85199. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85200. }
  85201. }
  85202. this._excludedMeshes[mesh.uniqueId] = null;
  85203. };
  85204. /**
  85205. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85206. * @param mesh mesh to test
  85207. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85208. */
  85209. HighlightLayer.prototype.hasMesh = function (mesh) {
  85210. if (!this._meshes) {
  85211. return false;
  85212. }
  85213. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85214. };
  85215. /**
  85216. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85217. * @param mesh The mesh to highlight
  85218. * @param color The color of the highlight
  85219. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85220. */
  85221. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85222. var _this = this;
  85223. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85224. if (!this._meshes) {
  85225. return;
  85226. }
  85227. var meshHighlight = this._meshes[mesh.uniqueId];
  85228. if (meshHighlight) {
  85229. meshHighlight.color = color;
  85230. }
  85231. else {
  85232. this._meshes[mesh.uniqueId] = {
  85233. mesh: mesh,
  85234. color: color,
  85235. // Lambda required for capture due to Observable this context
  85236. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85237. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85238. _this._defaultStencilReference(mesh);
  85239. }
  85240. else {
  85241. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85242. }
  85243. }),
  85244. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85245. glowEmissiveOnly: glowEmissiveOnly
  85246. };
  85247. }
  85248. this._shouldRender = true;
  85249. };
  85250. /**
  85251. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85252. * @param mesh The mesh to highlight
  85253. */
  85254. HighlightLayer.prototype.removeMesh = function (mesh) {
  85255. if (!this._meshes) {
  85256. return;
  85257. }
  85258. var meshHighlight = this._meshes[mesh.uniqueId];
  85259. if (meshHighlight) {
  85260. if (meshHighlight.observerHighlight) {
  85261. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85262. }
  85263. if (meshHighlight.observerDefault) {
  85264. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85265. }
  85266. delete this._meshes[mesh.uniqueId];
  85267. }
  85268. this._shouldRender = false;
  85269. for (var meshHighlightToCheck in this._meshes) {
  85270. if (this._meshes[meshHighlightToCheck]) {
  85271. this._shouldRender = true;
  85272. break;
  85273. }
  85274. }
  85275. };
  85276. /**
  85277. * Force the stencil to the normal expected value for none glowing parts
  85278. */
  85279. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85280. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85281. };
  85282. /**
  85283. * Free any resources and references associated to a mesh.
  85284. * Internal use
  85285. * @param mesh The mesh to free.
  85286. */
  85287. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85288. this.removeMesh(mesh);
  85289. this.removeExcludedMesh(mesh);
  85290. };
  85291. /**
  85292. * Dispose the highlight layer and free resources.
  85293. */
  85294. HighlightLayer.prototype.dispose = function () {
  85295. if (this._meshes) {
  85296. // Clean mesh references
  85297. for (var id in this._meshes) {
  85298. var meshHighlight = this._meshes[id];
  85299. if (meshHighlight && meshHighlight.mesh) {
  85300. if (meshHighlight.observerHighlight) {
  85301. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85302. }
  85303. if (meshHighlight.observerDefault) {
  85304. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85305. }
  85306. }
  85307. }
  85308. this._meshes = null;
  85309. }
  85310. if (this._excludedMeshes) {
  85311. for (var id in this._excludedMeshes) {
  85312. var meshHighlight = this._excludedMeshes[id];
  85313. if (meshHighlight) {
  85314. if (meshHighlight.beforeRender) {
  85315. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85316. }
  85317. if (meshHighlight.afterRender) {
  85318. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85319. }
  85320. }
  85321. }
  85322. this._excludedMeshes = null;
  85323. }
  85324. _super.prototype.dispose.call(this);
  85325. };
  85326. /**
  85327. * Effect Name of the highlight layer.
  85328. */
  85329. HighlightLayer.EffectName = "HighlightLayer";
  85330. /**
  85331. * The neutral color used during the preparation of the glow effect.
  85332. * This is black by default as the blend operation is a blend operation.
  85333. */
  85334. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85335. /**
  85336. * Stencil value used for glowing meshes.
  85337. */
  85338. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85339. /**
  85340. * Stencil value used for the other meshes in the scene.
  85341. */
  85342. HighlightLayer.NormalMeshStencilReference = 0x01;
  85343. return HighlightLayer;
  85344. }(BABYLON.EffectLayer));
  85345. BABYLON.HighlightLayer = HighlightLayer;
  85346. })(BABYLON || (BABYLON = {}));
  85347. //# sourceMappingURL=babylon.highlightLayer.js.map
  85348. var BABYLON;
  85349. (function (BABYLON) {
  85350. /**
  85351. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85352. *
  85353. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85354. * glowy meshes to your scene.
  85355. *
  85356. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85357. */
  85358. var GlowLayer = /** @class */ (function (_super) {
  85359. __extends(GlowLayer, _super);
  85360. /**
  85361. * Instantiates a new glow Layer and references it to the scene.
  85362. * @param name The name of the layer
  85363. * @param scene The scene to use the layer in
  85364. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85365. */
  85366. function GlowLayer(name, scene, options) {
  85367. var _this = _super.call(this, name, scene) || this;
  85368. _this.name = name;
  85369. _this._intensity = 1.0;
  85370. _this._includedOnlyMeshes = [];
  85371. _this._excludedMeshes = [];
  85372. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85373. // Adapt options
  85374. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85375. // Initialize the layer
  85376. _this._init({
  85377. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85378. camera: _this._options.camera,
  85379. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85380. mainTextureRatio: _this._options.mainTextureRatio
  85381. });
  85382. return _this;
  85383. }
  85384. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85385. /**
  85386. * Gets the kernel size of the blur.
  85387. */
  85388. get: function () {
  85389. return this._horizontalBlurPostprocess1.kernel;
  85390. },
  85391. /**
  85392. * Sets the kernel size of the blur.
  85393. */
  85394. set: function (value) {
  85395. this._horizontalBlurPostprocess1.kernel = value;
  85396. this._verticalBlurPostprocess1.kernel = value;
  85397. this._horizontalBlurPostprocess2.kernel = value;
  85398. this._verticalBlurPostprocess2.kernel = value;
  85399. },
  85400. enumerable: true,
  85401. configurable: true
  85402. });
  85403. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85404. /**
  85405. * Gets the glow intensity.
  85406. */
  85407. get: function () {
  85408. return this._intensity;
  85409. },
  85410. /**
  85411. * Sets the glow intensity.
  85412. */
  85413. set: function (value) {
  85414. this._intensity = value;
  85415. },
  85416. enumerable: true,
  85417. configurable: true
  85418. });
  85419. /**
  85420. * Get the effect name of the layer.
  85421. * @return The effect name
  85422. */
  85423. GlowLayer.prototype.getEffectName = function () {
  85424. return GlowLayer.EffectName;
  85425. };
  85426. /**
  85427. * Create the merge effect. This is the shader use to blit the information back
  85428. * to the main canvas at the end of the scene rendering.
  85429. */
  85430. GlowLayer.prototype._createMergeEffect = function () {
  85431. // Effect
  85432. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85433. };
  85434. /**
  85435. * Creates the render target textures and post processes used in the glow layer.
  85436. */
  85437. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85438. var _this = this;
  85439. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85440. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85441. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85442. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85443. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85444. width: blurTextureWidth,
  85445. height: blurTextureHeight
  85446. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85447. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85448. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85449. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85450. this._blurTexture1.renderParticles = false;
  85451. this._blurTexture1.ignoreCameraViewport = true;
  85452. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85453. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85454. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85455. width: blurTextureWidth2,
  85456. height: blurTextureHeight2
  85457. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85458. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85459. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85460. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85461. this._blurTexture2.renderParticles = false;
  85462. this._blurTexture2.ignoreCameraViewport = true;
  85463. this._textures = [this._blurTexture1, this._blurTexture2];
  85464. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85465. width: blurTextureWidth,
  85466. height: blurTextureHeight
  85467. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85468. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85469. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85470. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85471. effect.setTexture("textureSampler", _this._mainTexture);
  85472. });
  85473. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85474. width: blurTextureWidth,
  85475. height: blurTextureHeight
  85476. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85477. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85478. width: blurTextureWidth2,
  85479. height: blurTextureHeight2
  85480. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85481. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85482. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85483. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85484. effect.setTexture("textureSampler", _this._blurTexture1);
  85485. });
  85486. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85487. width: blurTextureWidth2,
  85488. height: blurTextureHeight2
  85489. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85490. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85491. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85492. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85493. this._mainTexture.samples = this._options.mainTextureSamples;
  85494. this._mainTexture.onAfterUnbindObservable.add(function () {
  85495. var internalTexture = _this._blurTexture1.getInternalTexture();
  85496. if (internalTexture) {
  85497. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85498. internalTexture = _this._blurTexture2.getInternalTexture();
  85499. if (internalTexture) {
  85500. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85501. }
  85502. }
  85503. });
  85504. // Prevent autoClear.
  85505. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85506. };
  85507. /**
  85508. * Checks for the readiness of the element composing the layer.
  85509. * @param subMesh the mesh to check for
  85510. * @param useInstances specify wether or not to use instances to render the mesh
  85511. * @param emissiveTexture the associated emissive texture used to generate the glow
  85512. * @return true if ready otherwise, false
  85513. */
  85514. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85515. var material = subMesh.getMaterial();
  85516. var mesh = subMesh.getRenderingMesh();
  85517. if (!material || !mesh) {
  85518. return false;
  85519. }
  85520. var emissiveTexture = material.emissiveTexture;
  85521. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85522. };
  85523. /**
  85524. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85525. */
  85526. GlowLayer.prototype.needStencil = function () {
  85527. return false;
  85528. };
  85529. /**
  85530. * Implementation specific of rendering the generating effect on the main canvas.
  85531. * @param effect The effect used to render through
  85532. */
  85533. GlowLayer.prototype._internalRender = function (effect) {
  85534. // Texture
  85535. effect.setTexture("textureSampler", this._blurTexture1);
  85536. effect.setTexture("textureSampler2", this._blurTexture2);
  85537. effect.setFloat("offset", this._intensity);
  85538. // Cache
  85539. var engine = this._engine;
  85540. var previousStencilBuffer = engine.getStencilBuffer();
  85541. // Draw order
  85542. engine.setStencilBuffer(false);
  85543. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85544. // Draw order
  85545. engine.setStencilBuffer(previousStencilBuffer);
  85546. };
  85547. /**
  85548. * Sets the required values for both the emissive texture and and the main color.
  85549. */
  85550. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85551. var textureLevel = 1.0;
  85552. if (this.customEmissiveTextureSelector) {
  85553. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85554. }
  85555. else {
  85556. if (material) {
  85557. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85558. if (this._emissiveTextureAndColor.texture) {
  85559. textureLevel = this._emissiveTextureAndColor.texture.level;
  85560. }
  85561. }
  85562. else {
  85563. this._emissiveTextureAndColor.texture = null;
  85564. }
  85565. }
  85566. if (this.customEmissiveColorSelector) {
  85567. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85568. }
  85569. else {
  85570. if (material.emissiveColor) {
  85571. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85572. }
  85573. else {
  85574. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85575. }
  85576. }
  85577. };
  85578. /**
  85579. * Returns true if the mesh should render, otherwise false.
  85580. * @param mesh The mesh to render
  85581. * @returns true if it should render otherwise false
  85582. */
  85583. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85584. return this.hasMesh(mesh);
  85585. };
  85586. /**
  85587. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85588. * @param mesh The mesh to exclude from the glow layer
  85589. */
  85590. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85591. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85592. this._excludedMeshes.push(mesh.uniqueId);
  85593. }
  85594. };
  85595. /**
  85596. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85597. * @param mesh The mesh to remove
  85598. */
  85599. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85600. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85601. if (index !== -1) {
  85602. this._excludedMeshes.splice(index, 1);
  85603. }
  85604. };
  85605. /**
  85606. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85607. * @param mesh The mesh to include in the glow layer
  85608. */
  85609. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85610. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85611. this._includedOnlyMeshes.push(mesh.uniqueId);
  85612. }
  85613. };
  85614. /**
  85615. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85616. * @param mesh The mesh to remove
  85617. */
  85618. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85619. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85620. if (index !== -1) {
  85621. this._includedOnlyMeshes.splice(index, 1);
  85622. }
  85623. };
  85624. /**
  85625. * Determine if a given mesh will be used in the glow layer
  85626. * @param mesh The mesh to test
  85627. * @returns true if the mesh will be highlighted by the current glow layer
  85628. */
  85629. GlowLayer.prototype.hasMesh = function (mesh) {
  85630. // Included Mesh
  85631. if (this._includedOnlyMeshes.length) {
  85632. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85633. }
  85634. ;
  85635. // Excluded Mesh
  85636. if (this._excludedMeshes.length) {
  85637. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85638. }
  85639. ;
  85640. return true;
  85641. };
  85642. /**
  85643. * Free any resources and references associated to a mesh.
  85644. * Internal use
  85645. * @param mesh The mesh to free.
  85646. */
  85647. GlowLayer.prototype._disposeMesh = function (mesh) {
  85648. this.removeIncludedOnlyMesh(mesh);
  85649. this.removeExcludedMesh(mesh);
  85650. };
  85651. /**
  85652. * Effect Name of the layer.
  85653. */
  85654. GlowLayer.EffectName = "GlowLayer";
  85655. /**
  85656. * The default blur kernel size used for the glow.
  85657. */
  85658. GlowLayer.DefaultBlurKernelSize = 32;
  85659. /**
  85660. * The default texture size ratio used for the glow.
  85661. */
  85662. GlowLayer.DefaultTextureRatio = 0.5;
  85663. return GlowLayer;
  85664. }(BABYLON.EffectLayer));
  85665. BABYLON.GlowLayer = GlowLayer;
  85666. })(BABYLON || (BABYLON = {}));
  85667. //# sourceMappingURL=babylon.glowLayer.js.map
  85668. var BABYLON;
  85669. (function (BABYLON) {
  85670. /**
  85671. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85672. */
  85673. var AssetTaskState;
  85674. (function (AssetTaskState) {
  85675. /**
  85676. * Initialization
  85677. */
  85678. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85679. /**
  85680. * Running
  85681. */
  85682. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85683. /**
  85684. * Done
  85685. */
  85686. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85687. /**
  85688. * Error
  85689. */
  85690. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85691. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85692. /**
  85693. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85694. */
  85695. var AbstractAssetTask = /** @class */ (function () {
  85696. /**
  85697. * Creates a new {BABYLON.AssetsManager}
  85698. * @param name defines the name of the task
  85699. */
  85700. function AbstractAssetTask(
  85701. /**
  85702. * Task name
  85703. */ name) {
  85704. this.name = name;
  85705. this._isCompleted = false;
  85706. this._taskState = AssetTaskState.INIT;
  85707. }
  85708. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85709. /**
  85710. * Get if the task is completed
  85711. */
  85712. get: function () {
  85713. return this._isCompleted;
  85714. },
  85715. enumerable: true,
  85716. configurable: true
  85717. });
  85718. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85719. /**
  85720. * Gets the current state of the task
  85721. */
  85722. get: function () {
  85723. return this._taskState;
  85724. },
  85725. enumerable: true,
  85726. configurable: true
  85727. });
  85728. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85729. /**
  85730. * Gets the current error object (if task is in error)
  85731. */
  85732. get: function () {
  85733. return this._errorObject;
  85734. },
  85735. enumerable: true,
  85736. configurable: true
  85737. });
  85738. /**
  85739. * Internal only
  85740. * @ignore
  85741. */
  85742. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85743. if (this._errorObject) {
  85744. return;
  85745. }
  85746. this._errorObject = {
  85747. message: message,
  85748. exception: exception
  85749. };
  85750. };
  85751. /**
  85752. * Execute the current task
  85753. * @param scene defines the scene where you want your assets to be loaded
  85754. * @param onSuccess is a callback called when the task is successfully executed
  85755. * @param onError is a callback called if an error occurs
  85756. */
  85757. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85758. var _this = this;
  85759. this._taskState = AssetTaskState.RUNNING;
  85760. this.runTask(scene, function () {
  85761. _this.onDoneCallback(onSuccess, onError);
  85762. }, function (msg, exception) {
  85763. _this.onErrorCallback(onError, msg, exception);
  85764. });
  85765. };
  85766. /**
  85767. * Execute the current task
  85768. * @param scene defines the scene where you want your assets to be loaded
  85769. * @param onSuccess is a callback called when the task is successfully executed
  85770. * @param onError is a callback called if an error occurs
  85771. */
  85772. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85773. throw new Error("runTask is not implemented");
  85774. };
  85775. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85776. this._taskState = AssetTaskState.ERROR;
  85777. this._errorObject = {
  85778. message: message,
  85779. exception: exception
  85780. };
  85781. if (this.onError) {
  85782. this.onError(this, message, exception);
  85783. }
  85784. onError();
  85785. };
  85786. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85787. try {
  85788. this._taskState = AssetTaskState.DONE;
  85789. this._isCompleted = true;
  85790. if (this.onSuccess) {
  85791. this.onSuccess(this);
  85792. }
  85793. onSuccess();
  85794. }
  85795. catch (e) {
  85796. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85797. }
  85798. };
  85799. return AbstractAssetTask;
  85800. }());
  85801. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85802. /**
  85803. * Class used to share progress information about assets loading
  85804. */
  85805. var AssetsProgressEvent = /** @class */ (function () {
  85806. /**
  85807. * Creates a {BABYLON.AssetsProgressEvent}
  85808. * @param remainingCount defines the number of remaining tasks to process
  85809. * @param totalCount defines the total number of tasks
  85810. * @param task defines the task that was just processed
  85811. */
  85812. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85813. this.remainingCount = remainingCount;
  85814. this.totalCount = totalCount;
  85815. this.task = task;
  85816. }
  85817. return AssetsProgressEvent;
  85818. }());
  85819. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85820. /**
  85821. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85822. */
  85823. var MeshAssetTask = /** @class */ (function (_super) {
  85824. __extends(MeshAssetTask, _super);
  85825. /**
  85826. * Creates a new {BABYLON.MeshAssetTask}
  85827. * @param name defines the name of the task
  85828. * @param meshesNames defines the list of mesh's names you want to load
  85829. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85830. * @param sceneFilename defines the filename of the scene to load from
  85831. */
  85832. function MeshAssetTask(
  85833. /**
  85834. * Defines the name of the task
  85835. */
  85836. name,
  85837. /**
  85838. * Defines the list of mesh's names you want to load
  85839. */
  85840. meshesNames,
  85841. /**
  85842. * Defines the root url to use as a base to load your meshes and associated resources
  85843. */
  85844. rootUrl,
  85845. /**
  85846. * Defines the filename of the scene to load from
  85847. */
  85848. sceneFilename) {
  85849. var _this = _super.call(this, name) || this;
  85850. _this.name = name;
  85851. _this.meshesNames = meshesNames;
  85852. _this.rootUrl = rootUrl;
  85853. _this.sceneFilename = sceneFilename;
  85854. return _this;
  85855. }
  85856. /**
  85857. * Execute the current task
  85858. * @param scene defines the scene where you want your assets to be loaded
  85859. * @param onSuccess is a callback called when the task is successfully executed
  85860. * @param onError is a callback called if an error occurs
  85861. */
  85862. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85863. var _this = this;
  85864. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85865. _this.loadedMeshes = meshes;
  85866. _this.loadedParticleSystems = particleSystems;
  85867. _this.loadedSkeletons = skeletons;
  85868. onSuccess();
  85869. }, null, function (scene, message, exception) {
  85870. onError(message, exception);
  85871. });
  85872. };
  85873. return MeshAssetTask;
  85874. }(AbstractAssetTask));
  85875. BABYLON.MeshAssetTask = MeshAssetTask;
  85876. /**
  85877. * Define a task used by {BABYLON.AssetsManager} to load text content
  85878. */
  85879. var TextFileAssetTask = /** @class */ (function (_super) {
  85880. __extends(TextFileAssetTask, _super);
  85881. /**
  85882. * Creates a new TextFileAssetTask object
  85883. * @param name defines the name of the task
  85884. * @param url defines the location of the file to load
  85885. */
  85886. function TextFileAssetTask(
  85887. /**
  85888. * Defines the name of the task
  85889. */
  85890. name,
  85891. /**
  85892. * Defines the location of the file to load
  85893. */
  85894. url) {
  85895. var _this = _super.call(this, name) || this;
  85896. _this.name = name;
  85897. _this.url = url;
  85898. return _this;
  85899. }
  85900. /**
  85901. * Execute the current task
  85902. * @param scene defines the scene where you want your assets to be loaded
  85903. * @param onSuccess is a callback called when the task is successfully executed
  85904. * @param onError is a callback called if an error occurs
  85905. */
  85906. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85907. var _this = this;
  85908. scene._loadFile(this.url, function (data) {
  85909. _this.text = data;
  85910. onSuccess();
  85911. }, undefined, false, false, function (request, exception) {
  85912. if (request) {
  85913. onError(request.status + " " + request.statusText, exception);
  85914. }
  85915. });
  85916. };
  85917. return TextFileAssetTask;
  85918. }(AbstractAssetTask));
  85919. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85920. /**
  85921. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85922. */
  85923. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85924. __extends(BinaryFileAssetTask, _super);
  85925. /**
  85926. * Creates a new BinaryFileAssetTask object
  85927. * @param name defines the name of the new task
  85928. * @param url defines the location of the file to load
  85929. */
  85930. function BinaryFileAssetTask(
  85931. /**
  85932. * Defines the name of the task
  85933. */
  85934. name,
  85935. /**
  85936. * Defines the location of the file to load
  85937. */
  85938. url) {
  85939. var _this = _super.call(this, name) || this;
  85940. _this.name = name;
  85941. _this.url = url;
  85942. return _this;
  85943. }
  85944. /**
  85945. * Execute the current task
  85946. * @param scene defines the scene where you want your assets to be loaded
  85947. * @param onSuccess is a callback called when the task is successfully executed
  85948. * @param onError is a callback called if an error occurs
  85949. */
  85950. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85951. var _this = this;
  85952. scene._loadFile(this.url, function (data) {
  85953. _this.data = data;
  85954. onSuccess();
  85955. }, undefined, true, true, function (request, exception) {
  85956. if (request) {
  85957. onError(request.status + " " + request.statusText, exception);
  85958. }
  85959. });
  85960. };
  85961. return BinaryFileAssetTask;
  85962. }(AbstractAssetTask));
  85963. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85964. /**
  85965. * Define a task used by {BABYLON.AssetsManager} to load images
  85966. */
  85967. var ImageAssetTask = /** @class */ (function (_super) {
  85968. __extends(ImageAssetTask, _super);
  85969. /**
  85970. * Creates a new ImageAssetTask
  85971. * @param name defines the name of the task
  85972. * @param url defines the location of the image to load
  85973. */
  85974. function ImageAssetTask(
  85975. /**
  85976. * Defines the name of the task
  85977. */
  85978. name,
  85979. /**
  85980. * Defines the location of the image to load
  85981. */
  85982. url) {
  85983. var _this = _super.call(this, name) || this;
  85984. _this.name = name;
  85985. _this.url = url;
  85986. return _this;
  85987. }
  85988. /**
  85989. * Execute the current task
  85990. * @param scene defines the scene where you want your assets to be loaded
  85991. * @param onSuccess is a callback called when the task is successfully executed
  85992. * @param onError is a callback called if an error occurs
  85993. */
  85994. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85995. var _this = this;
  85996. var img = new Image();
  85997. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85998. img.onload = function () {
  85999. _this.image = img;
  86000. onSuccess();
  86001. };
  86002. img.onerror = function (err) {
  86003. onError("Error loading image", err);
  86004. };
  86005. img.src = this.url;
  86006. };
  86007. return ImageAssetTask;
  86008. }(AbstractAssetTask));
  86009. BABYLON.ImageAssetTask = ImageAssetTask;
  86010. /**
  86011. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86012. */
  86013. var TextureAssetTask = /** @class */ (function (_super) {
  86014. __extends(TextureAssetTask, _super);
  86015. /**
  86016. * Creates a new TextureAssetTask object
  86017. * @param name defines the name of the task
  86018. * @param url defines the location of the file to load
  86019. * @param noMipmap defines if mipmap should not be generated (default is false)
  86020. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86021. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86022. */
  86023. function TextureAssetTask(
  86024. /**
  86025. * Defines the name of the task
  86026. */
  86027. name,
  86028. /**
  86029. * Defines the location of the file to load
  86030. */
  86031. url,
  86032. /**
  86033. * Defines if mipmap should not be generated (default is false)
  86034. */
  86035. noMipmap,
  86036. /**
  86037. * Defines if texture must be inverted on Y axis (default is false)
  86038. */
  86039. invertY,
  86040. /**
  86041. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86042. */
  86043. samplingMode) {
  86044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86045. var _this = _super.call(this, name) || this;
  86046. _this.name = name;
  86047. _this.url = url;
  86048. _this.noMipmap = noMipmap;
  86049. _this.invertY = invertY;
  86050. _this.samplingMode = samplingMode;
  86051. return _this;
  86052. }
  86053. /**
  86054. * Execute the current task
  86055. * @param scene defines the scene where you want your assets to be loaded
  86056. * @param onSuccess is a callback called when the task is successfully executed
  86057. * @param onError is a callback called if an error occurs
  86058. */
  86059. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86060. var onload = function () {
  86061. onSuccess();
  86062. };
  86063. var onerror = function (message, exception) {
  86064. onError(message, exception);
  86065. };
  86066. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86067. };
  86068. return TextureAssetTask;
  86069. }(AbstractAssetTask));
  86070. BABYLON.TextureAssetTask = TextureAssetTask;
  86071. /**
  86072. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86073. */
  86074. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86075. __extends(CubeTextureAssetTask, _super);
  86076. /**
  86077. * Creates a new CubeTextureAssetTask
  86078. * @param name defines the name of the task
  86079. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86080. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86081. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86082. * @param files defines the explicit list of files (undefined by default)
  86083. */
  86084. function CubeTextureAssetTask(
  86085. /**
  86086. * Defines the name of the task
  86087. */
  86088. name,
  86089. /**
  86090. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86091. */
  86092. url,
  86093. /**
  86094. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86095. */
  86096. extensions,
  86097. /**
  86098. * Defines if mipmaps should not be generated (default is false)
  86099. */
  86100. noMipmap,
  86101. /**
  86102. * Defines the explicit list of files (undefined by default)
  86103. */
  86104. files) {
  86105. var _this = _super.call(this, name) || this;
  86106. _this.name = name;
  86107. _this.url = url;
  86108. _this.extensions = extensions;
  86109. _this.noMipmap = noMipmap;
  86110. _this.files = files;
  86111. return _this;
  86112. }
  86113. /**
  86114. * Execute the current task
  86115. * @param scene defines the scene where you want your assets to be loaded
  86116. * @param onSuccess is a callback called when the task is successfully executed
  86117. * @param onError is a callback called if an error occurs
  86118. */
  86119. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86120. var onload = function () {
  86121. onSuccess();
  86122. };
  86123. var onerror = function (message, exception) {
  86124. onError(message, exception);
  86125. };
  86126. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86127. };
  86128. return CubeTextureAssetTask;
  86129. }(AbstractAssetTask));
  86130. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86131. /**
  86132. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86133. */
  86134. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86135. __extends(HDRCubeTextureAssetTask, _super);
  86136. /**
  86137. * Creates a new HDRCubeTextureAssetTask object
  86138. * @param name defines the name of the task
  86139. * @param url defines the location of the file to load
  86140. * @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.
  86141. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86142. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86143. * @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)
  86144. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86145. */
  86146. function HDRCubeTextureAssetTask(
  86147. /**
  86148. * Defines the name of the task
  86149. */
  86150. name,
  86151. /**
  86152. * Defines the location of the file to load
  86153. */
  86154. url,
  86155. /**
  86156. * 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.
  86157. */
  86158. size,
  86159. /**
  86160. * Defines if mipmaps should not be generated (default is false)
  86161. */
  86162. noMipmap,
  86163. /**
  86164. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86165. */
  86166. generateHarmonics,
  86167. /**
  86168. * 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)
  86169. */
  86170. useInGammaSpace,
  86171. /**
  86172. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86173. */
  86174. usePMREMGenerator) {
  86175. if (noMipmap === void 0) { noMipmap = false; }
  86176. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86177. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86178. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86179. var _this = _super.call(this, name) || this;
  86180. _this.name = name;
  86181. _this.url = url;
  86182. _this.size = size;
  86183. _this.noMipmap = noMipmap;
  86184. _this.generateHarmonics = generateHarmonics;
  86185. _this.useInGammaSpace = useInGammaSpace;
  86186. _this.usePMREMGenerator = usePMREMGenerator;
  86187. return _this;
  86188. }
  86189. /**
  86190. * Execute the current task
  86191. * @param scene defines the scene where you want your assets to be loaded
  86192. * @param onSuccess is a callback called when the task is successfully executed
  86193. * @param onError is a callback called if an error occurs
  86194. */
  86195. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86196. var onload = function () {
  86197. onSuccess();
  86198. };
  86199. var onerror = function (message, exception) {
  86200. onError(message, exception);
  86201. };
  86202. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86203. };
  86204. return HDRCubeTextureAssetTask;
  86205. }(AbstractAssetTask));
  86206. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86207. /**
  86208. * This class can be used to easily import assets into a scene
  86209. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86210. */
  86211. var AssetsManager = /** @class */ (function () {
  86212. /**
  86213. * Creates a new AssetsManager
  86214. * @param scene defines the scene to work on
  86215. */
  86216. function AssetsManager(scene) {
  86217. this._isLoading = false;
  86218. this._tasks = new Array();
  86219. this._waitingTasksCount = 0;
  86220. this._totalTasksCount = 0;
  86221. /**
  86222. * Observable called when all tasks are processed
  86223. */
  86224. this.onTaskSuccessObservable = new BABYLON.Observable();
  86225. /**
  86226. * Observable called when a task had an error
  86227. */
  86228. this.onTaskErrorObservable = new BABYLON.Observable();
  86229. /**
  86230. * Observable called when a task is successful
  86231. */
  86232. this.onTasksDoneObservable = new BABYLON.Observable();
  86233. /**
  86234. * Observable called when a task is done (whatever the result is)
  86235. */
  86236. this.onProgressObservable = new BABYLON.Observable();
  86237. /**
  86238. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86239. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86240. */
  86241. this.useDefaultLoadingScreen = true;
  86242. this._scene = scene;
  86243. }
  86244. /**
  86245. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86246. * @param taskName defines the name of the new task
  86247. * @param meshesNames defines the name of meshes to load
  86248. * @param rootUrl defines the root url to use to locate files
  86249. * @param sceneFilename defines the filename of the scene file
  86250. * @returns a new {BABYLON.MeshAssetTask} object
  86251. */
  86252. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86253. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86254. this._tasks.push(task);
  86255. return task;
  86256. };
  86257. /**
  86258. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86259. * @param taskName defines the name of the new task
  86260. * @param url defines the url of the file to load
  86261. * @returns a new {BABYLON.TextFileAssetTask} object
  86262. */
  86263. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86264. var task = new TextFileAssetTask(taskName, url);
  86265. this._tasks.push(task);
  86266. return task;
  86267. };
  86268. /**
  86269. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86270. * @param taskName defines the name of the new task
  86271. * @param url defines the url of the file to load
  86272. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86273. */
  86274. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86275. var task = new BinaryFileAssetTask(taskName, url);
  86276. this._tasks.push(task);
  86277. return task;
  86278. };
  86279. /**
  86280. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86281. * @param taskName defines the name of the new task
  86282. * @param url defines the url of the file to load
  86283. * @returns a new {BABYLON.ImageAssetTask} object
  86284. */
  86285. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86286. var task = new ImageAssetTask(taskName, url);
  86287. this._tasks.push(task);
  86288. return task;
  86289. };
  86290. /**
  86291. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86292. * @param taskName defines the name of the new task
  86293. * @param url defines the url of the file to load
  86294. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86295. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86296. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86297. * @returns a new {BABYLON.TextureAssetTask} object
  86298. */
  86299. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86301. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86302. this._tasks.push(task);
  86303. return task;
  86304. };
  86305. /**
  86306. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86307. * @param taskName defines the name of the new task
  86308. * @param url defines the url of the file to load
  86309. * @param extensions defines the extension to use to load the cube map (can be null)
  86310. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86311. * @param files defines the list of files to load (can be null)
  86312. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86313. */
  86314. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86315. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86316. this._tasks.push(task);
  86317. return task;
  86318. };
  86319. /**
  86320. *
  86321. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86322. * @param taskName defines the name of the new task
  86323. * @param url defines the url of the file to load
  86324. * @param size defines the size you want for the cubemap (can be null)
  86325. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86326. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86327. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86328. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86329. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86330. */
  86331. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86332. if (noMipmap === void 0) { noMipmap = false; }
  86333. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86334. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86335. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86336. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86337. this._tasks.push(task);
  86338. return task;
  86339. };
  86340. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86341. var _this = this;
  86342. this._waitingTasksCount--;
  86343. try {
  86344. if (task.taskState === AssetTaskState.DONE) {
  86345. // Let's remove successfull tasks
  86346. BABYLON.Tools.SetImmediate(function () {
  86347. var index = _this._tasks.indexOf(task);
  86348. if (index > -1) {
  86349. _this._tasks.splice(index, 1);
  86350. }
  86351. });
  86352. }
  86353. if (this.onProgress) {
  86354. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86355. }
  86356. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86357. }
  86358. catch (e) {
  86359. BABYLON.Tools.Error("Error running progress callbacks.");
  86360. console.log(e);
  86361. }
  86362. if (this._waitingTasksCount === 0) {
  86363. try {
  86364. if (this.onFinish) {
  86365. this.onFinish(this._tasks);
  86366. }
  86367. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86368. }
  86369. catch (e) {
  86370. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86371. console.log(e);
  86372. }
  86373. this._isLoading = false;
  86374. this._scene.getEngine().hideLoadingUI();
  86375. }
  86376. };
  86377. AssetsManager.prototype._runTask = function (task) {
  86378. var _this = this;
  86379. var done = function () {
  86380. try {
  86381. if (_this.onTaskSuccess) {
  86382. _this.onTaskSuccess(task);
  86383. }
  86384. _this.onTaskSuccessObservable.notifyObservers(task);
  86385. _this._decreaseWaitingTasksCount(task);
  86386. }
  86387. catch (e) {
  86388. error("Error executing task success callbacks", e);
  86389. }
  86390. };
  86391. var error = function (message, exception) {
  86392. task._setErrorObject(message, exception);
  86393. if (_this.onTaskError) {
  86394. _this.onTaskError(task);
  86395. }
  86396. _this.onTaskErrorObservable.notifyObservers(task);
  86397. _this._decreaseWaitingTasksCount(task);
  86398. };
  86399. task.run(this._scene, done, error);
  86400. };
  86401. /**
  86402. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86403. * @return the current instance of the {BABYLON.AssetsManager}
  86404. */
  86405. AssetsManager.prototype.reset = function () {
  86406. this._isLoading = false;
  86407. this._tasks = new Array();
  86408. return this;
  86409. };
  86410. /**
  86411. * Start the loading process
  86412. * @return the current instance of the {BABYLON.AssetsManager}
  86413. */
  86414. AssetsManager.prototype.load = function () {
  86415. if (this._isLoading) {
  86416. return this;
  86417. }
  86418. this._isLoading = true;
  86419. this._waitingTasksCount = this._tasks.length;
  86420. this._totalTasksCount = this._tasks.length;
  86421. if (this._waitingTasksCount === 0) {
  86422. this._isLoading = false;
  86423. if (this.onFinish) {
  86424. this.onFinish(this._tasks);
  86425. }
  86426. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86427. return this;
  86428. }
  86429. if (this.useDefaultLoadingScreen) {
  86430. this._scene.getEngine().displayLoadingUI();
  86431. }
  86432. for (var index = 0; index < this._tasks.length; index++) {
  86433. var task = this._tasks[index];
  86434. this._runTask(task);
  86435. }
  86436. return this;
  86437. };
  86438. return AssetsManager;
  86439. }());
  86440. BABYLON.AssetsManager = AssetsManager;
  86441. })(BABYLON || (BABYLON = {}));
  86442. //# sourceMappingURL=babylon.assetsManager.js.map
  86443. var BABYLON;
  86444. (function (BABYLON) {
  86445. var serializedGeometries = [];
  86446. var serializeGeometry = function (geometry, serializationGeometries) {
  86447. if (serializedGeometries[geometry.id]) {
  86448. return;
  86449. }
  86450. if (geometry.doNotSerialize) {
  86451. return;
  86452. }
  86453. if (geometry instanceof BABYLON.BoxGeometry) {
  86454. serializationGeometries.boxes.push(geometry.serialize());
  86455. }
  86456. else if (geometry instanceof BABYLON.SphereGeometry) {
  86457. serializationGeometries.spheres.push(geometry.serialize());
  86458. }
  86459. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86460. serializationGeometries.cylinders.push(geometry.serialize());
  86461. }
  86462. else if (geometry instanceof BABYLON.TorusGeometry) {
  86463. serializationGeometries.toruses.push(geometry.serialize());
  86464. }
  86465. else if (geometry instanceof BABYLON.GroundGeometry) {
  86466. serializationGeometries.grounds.push(geometry.serialize());
  86467. }
  86468. else if (geometry instanceof BABYLON.Plane) {
  86469. serializationGeometries.planes.push(geometry.serialize());
  86470. }
  86471. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86472. serializationGeometries.torusKnots.push(geometry.serialize());
  86473. }
  86474. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86475. throw new Error("Unknown primitive type");
  86476. }
  86477. else {
  86478. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86479. }
  86480. serializedGeometries[geometry.id] = true;
  86481. };
  86482. var serializeMesh = function (mesh, serializationScene) {
  86483. var serializationObject = {};
  86484. // Geometry
  86485. var geometry = mesh._geometry;
  86486. if (geometry) {
  86487. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86488. // 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
  86489. serializeGeometry(geometry, serializationScene.geometries);
  86490. }
  86491. }
  86492. // Custom
  86493. if (mesh.serialize) {
  86494. mesh.serialize(serializationObject);
  86495. }
  86496. return serializationObject;
  86497. };
  86498. var finalizeSingleMesh = function (mesh, serializationObject) {
  86499. //only works if the mesh is already loaded
  86500. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86501. //serialize material
  86502. if (mesh.material) {
  86503. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86504. serializationObject.materials = serializationObject.materials || [];
  86505. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86506. serializationObject.materials.push(mesh.material.serialize());
  86507. }
  86508. }
  86509. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86510. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86511. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86512. serializationObject.multiMaterials.push(mesh.material.serialize());
  86513. }
  86514. }
  86515. }
  86516. //serialize geometry
  86517. var geometry = mesh._geometry;
  86518. if (geometry) {
  86519. if (!serializationObject.geometries) {
  86520. serializationObject.geometries = {};
  86521. serializationObject.geometries.boxes = [];
  86522. serializationObject.geometries.spheres = [];
  86523. serializationObject.geometries.cylinders = [];
  86524. serializationObject.geometries.toruses = [];
  86525. serializationObject.geometries.grounds = [];
  86526. serializationObject.geometries.planes = [];
  86527. serializationObject.geometries.torusKnots = [];
  86528. serializationObject.geometries.vertexData = [];
  86529. }
  86530. serializeGeometry(geometry, serializationObject.geometries);
  86531. }
  86532. // Skeletons
  86533. if (mesh.skeleton) {
  86534. serializationObject.skeletons = serializationObject.skeletons || [];
  86535. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86536. }
  86537. //serialize the actual mesh
  86538. serializationObject.meshes = serializationObject.meshes || [];
  86539. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86540. }
  86541. };
  86542. var SceneSerializer = /** @class */ (function () {
  86543. function SceneSerializer() {
  86544. }
  86545. SceneSerializer.ClearCache = function () {
  86546. serializedGeometries = [];
  86547. };
  86548. SceneSerializer.Serialize = function (scene) {
  86549. var serializationObject = {};
  86550. SceneSerializer.ClearCache();
  86551. // Scene
  86552. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86553. serializationObject.autoClear = scene.autoClear;
  86554. serializationObject.clearColor = scene.clearColor.asArray();
  86555. serializationObject.ambientColor = scene.ambientColor.asArray();
  86556. serializationObject.gravity = scene.gravity.asArray();
  86557. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86558. serializationObject.workerCollisions = scene.workerCollisions;
  86559. // Fog
  86560. if (scene.fogMode && scene.fogMode !== 0) {
  86561. serializationObject.fogMode = scene.fogMode;
  86562. serializationObject.fogColor = scene.fogColor.asArray();
  86563. serializationObject.fogStart = scene.fogStart;
  86564. serializationObject.fogEnd = scene.fogEnd;
  86565. serializationObject.fogDensity = scene.fogDensity;
  86566. }
  86567. //Physics
  86568. if (scene.isPhysicsEnabled()) {
  86569. var physicEngine = scene.getPhysicsEngine();
  86570. if (physicEngine) {
  86571. serializationObject.physicsEnabled = true;
  86572. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86573. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86574. }
  86575. }
  86576. // Metadata
  86577. if (scene.metadata) {
  86578. serializationObject.metadata = scene.metadata;
  86579. }
  86580. // Morph targets
  86581. serializationObject.morphTargetManagers = [];
  86582. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86583. var abstractMesh = _a[_i];
  86584. var manager = abstractMesh.morphTargetManager;
  86585. if (manager) {
  86586. serializationObject.morphTargetManagers.push(manager.serialize());
  86587. }
  86588. }
  86589. // Lights
  86590. serializationObject.lights = [];
  86591. var index;
  86592. var light;
  86593. for (index = 0; index < scene.lights.length; index++) {
  86594. light = scene.lights[index];
  86595. if (!light.doNotSerialize) {
  86596. serializationObject.lights.push(light.serialize());
  86597. }
  86598. }
  86599. // Cameras
  86600. serializationObject.cameras = [];
  86601. for (index = 0; index < scene.cameras.length; index++) {
  86602. var camera = scene.cameras[index];
  86603. if (!camera.doNotSerialize) {
  86604. serializationObject.cameras.push(camera.serialize());
  86605. }
  86606. }
  86607. if (scene.activeCamera) {
  86608. serializationObject.activeCameraID = scene.activeCamera.id;
  86609. }
  86610. // Animations
  86611. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86612. // Materials
  86613. serializationObject.materials = [];
  86614. serializationObject.multiMaterials = [];
  86615. var material;
  86616. for (index = 0; index < scene.materials.length; index++) {
  86617. material = scene.materials[index];
  86618. if (!material.doNotSerialize) {
  86619. serializationObject.materials.push(material.serialize());
  86620. }
  86621. }
  86622. // MultiMaterials
  86623. serializationObject.multiMaterials = [];
  86624. for (index = 0; index < scene.multiMaterials.length; index++) {
  86625. var multiMaterial = scene.multiMaterials[index];
  86626. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86627. }
  86628. // Environment texture
  86629. if (scene.environmentTexture) {
  86630. serializationObject.environmentTexture = scene.environmentTexture.name;
  86631. }
  86632. // Skeletons
  86633. serializationObject.skeletons = [];
  86634. for (index = 0; index < scene.skeletons.length; index++) {
  86635. var skeleton = scene.skeletons[index];
  86636. if (!skeleton.doNotSerialize) {
  86637. serializationObject.skeletons.push(skeleton.serialize());
  86638. }
  86639. }
  86640. // Transform nodes
  86641. serializationObject.transformNodes = [];
  86642. for (index = 0; index < scene.transformNodes.length; index++) {
  86643. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86644. }
  86645. // Geometries
  86646. serializationObject.geometries = {};
  86647. serializationObject.geometries.boxes = [];
  86648. serializationObject.geometries.spheres = [];
  86649. serializationObject.geometries.cylinders = [];
  86650. serializationObject.geometries.toruses = [];
  86651. serializationObject.geometries.grounds = [];
  86652. serializationObject.geometries.planes = [];
  86653. serializationObject.geometries.torusKnots = [];
  86654. serializationObject.geometries.vertexData = [];
  86655. serializedGeometries = [];
  86656. var geometries = scene.getGeometries();
  86657. for (index = 0; index < geometries.length; index++) {
  86658. var geometry = geometries[index];
  86659. if (geometry.isReady()) {
  86660. serializeGeometry(geometry, serializationObject.geometries);
  86661. }
  86662. }
  86663. // Meshes
  86664. serializationObject.meshes = [];
  86665. for (index = 0; index < scene.meshes.length; index++) {
  86666. var abstractMesh = scene.meshes[index];
  86667. if (abstractMesh instanceof BABYLON.Mesh) {
  86668. var mesh = abstractMesh;
  86669. if (!mesh.doNotSerialize) {
  86670. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86671. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86672. }
  86673. }
  86674. }
  86675. }
  86676. // Particles Systems
  86677. serializationObject.particleSystems = [];
  86678. for (index = 0; index < scene.particleSystems.length; index++) {
  86679. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86680. }
  86681. // Lens flares
  86682. serializationObject.lensFlareSystems = [];
  86683. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86684. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86685. }
  86686. // Shadows
  86687. serializationObject.shadowGenerators = [];
  86688. for (index = 0; index < scene.lights.length; index++) {
  86689. light = scene.lights[index];
  86690. var shadowGenerator = light.getShadowGenerator();
  86691. if (shadowGenerator) {
  86692. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86693. }
  86694. }
  86695. // Action Manager
  86696. if (scene.actionManager) {
  86697. serializationObject.actions = scene.actionManager.serialize("scene");
  86698. }
  86699. // Audio
  86700. serializationObject.sounds = [];
  86701. for (index = 0; index < scene.soundTracks.length; index++) {
  86702. var soundtrack = scene.soundTracks[index];
  86703. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86704. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86705. }
  86706. }
  86707. return serializationObject;
  86708. };
  86709. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86710. if (withParents === void 0) { withParents = false; }
  86711. if (withChildren === void 0) { withChildren = false; }
  86712. var serializationObject = {};
  86713. SceneSerializer.ClearCache();
  86714. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86715. if (withParents || withChildren) {
  86716. //deliberate for loop! not for each, appended should be processed as well.
  86717. for (var i = 0; i < toSerialize.length; ++i) {
  86718. if (withChildren) {
  86719. toSerialize[i].getDescendants().forEach(function (node) {
  86720. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86721. toSerialize.push(node);
  86722. }
  86723. });
  86724. }
  86725. //make sure the array doesn't contain the object already
  86726. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86727. toSerialize.push(toSerialize[i].parent);
  86728. }
  86729. }
  86730. }
  86731. toSerialize.forEach(function (mesh) {
  86732. finalizeSingleMesh(mesh, serializationObject);
  86733. });
  86734. return serializationObject;
  86735. };
  86736. return SceneSerializer;
  86737. }());
  86738. BABYLON.SceneSerializer = SceneSerializer;
  86739. })(BABYLON || (BABYLON = {}));
  86740. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86741. var BABYLON;
  86742. (function (BABYLON) {
  86743. var ReflectionProbe = /** @class */ (function () {
  86744. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86745. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86746. var _this = this;
  86747. this.name = name;
  86748. this._viewMatrix = BABYLON.Matrix.Identity();
  86749. this._target = BABYLON.Vector3.Zero();
  86750. this._add = BABYLON.Vector3.Zero();
  86751. this._invertYAxis = false;
  86752. this.position = BABYLON.Vector3.Zero();
  86753. this._scene = scene;
  86754. this._scene.reflectionProbes.push(this);
  86755. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86756. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86757. switch (faceIndex) {
  86758. case 0:
  86759. _this._add.copyFromFloats(1, 0, 0);
  86760. break;
  86761. case 1:
  86762. _this._add.copyFromFloats(-1, 0, 0);
  86763. break;
  86764. case 2:
  86765. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86766. break;
  86767. case 3:
  86768. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86769. break;
  86770. case 4:
  86771. _this._add.copyFromFloats(0, 0, 1);
  86772. break;
  86773. case 5:
  86774. _this._add.copyFromFloats(0, 0, -1);
  86775. break;
  86776. }
  86777. if (_this._attachedMesh) {
  86778. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86779. }
  86780. _this.position.addToRef(_this._add, _this._target);
  86781. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86782. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86783. scene._forcedViewPosition = _this.position;
  86784. });
  86785. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86786. scene._forcedViewPosition = null;
  86787. scene.updateTransformMatrix(true);
  86788. });
  86789. if (scene.activeCamera) {
  86790. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86791. }
  86792. }
  86793. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86794. get: function () {
  86795. return this._renderTargetTexture.samples;
  86796. },
  86797. set: function (value) {
  86798. this._renderTargetTexture.samples = value;
  86799. },
  86800. enumerable: true,
  86801. configurable: true
  86802. });
  86803. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86804. get: function () {
  86805. return this._renderTargetTexture.refreshRate;
  86806. },
  86807. set: function (value) {
  86808. this._renderTargetTexture.refreshRate = value;
  86809. },
  86810. enumerable: true,
  86811. configurable: true
  86812. });
  86813. ReflectionProbe.prototype.getScene = function () {
  86814. return this._scene;
  86815. };
  86816. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86817. get: function () {
  86818. return this._renderTargetTexture;
  86819. },
  86820. enumerable: true,
  86821. configurable: true
  86822. });
  86823. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86824. get: function () {
  86825. return this._renderTargetTexture.renderList;
  86826. },
  86827. enumerable: true,
  86828. configurable: true
  86829. });
  86830. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86831. this._attachedMesh = mesh;
  86832. };
  86833. /**
  86834. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86835. *
  86836. * @param renderingGroupId The rendering group id corresponding to its index
  86837. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86838. */
  86839. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86840. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86841. };
  86842. ReflectionProbe.prototype.dispose = function () {
  86843. var index = this._scene.reflectionProbes.indexOf(this);
  86844. if (index !== -1) {
  86845. // Remove from the scene if found
  86846. this._scene.reflectionProbes.splice(index, 1);
  86847. }
  86848. if (this._renderTargetTexture) {
  86849. this._renderTargetTexture.dispose();
  86850. this._renderTargetTexture = null;
  86851. }
  86852. };
  86853. return ReflectionProbe;
  86854. }());
  86855. BABYLON.ReflectionProbe = ReflectionProbe;
  86856. })(BABYLON || (BABYLON = {}));
  86857. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86858. var BABYLON;
  86859. (function (BABYLON) {
  86860. var Layer = /** @class */ (function () {
  86861. function Layer(name, imgUrl, scene, isBackground, color) {
  86862. this.name = name;
  86863. this.scale = new BABYLON.Vector2(1, 1);
  86864. this.offset = new BABYLON.Vector2(0, 0);
  86865. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86866. this.layerMask = 0x0FFFFFFF;
  86867. this._vertexBuffers = {};
  86868. // Events
  86869. /**
  86870. * An event triggered when the layer is disposed.
  86871. * @type {BABYLON.Observable}
  86872. */
  86873. this.onDisposeObservable = new BABYLON.Observable();
  86874. /**
  86875. * An event triggered before rendering the scene
  86876. * @type {BABYLON.Observable}
  86877. */
  86878. this.onBeforeRenderObservable = new BABYLON.Observable();
  86879. /**
  86880. * An event triggered after rendering the scene
  86881. * @type {BABYLON.Observable}
  86882. */
  86883. this.onAfterRenderObservable = new BABYLON.Observable();
  86884. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86885. this.isBackground = isBackground === undefined ? true : isBackground;
  86886. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86887. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86888. this._scene.layers.push(this);
  86889. var engine = this._scene.getEngine();
  86890. // VBO
  86891. var vertices = [];
  86892. vertices.push(1, 1);
  86893. vertices.push(-1, 1);
  86894. vertices.push(-1, -1);
  86895. vertices.push(1, -1);
  86896. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86897. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86898. this._createIndexBuffer();
  86899. // Effects
  86900. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86901. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86902. }
  86903. Object.defineProperty(Layer.prototype, "onDispose", {
  86904. set: function (callback) {
  86905. if (this._onDisposeObserver) {
  86906. this.onDisposeObservable.remove(this._onDisposeObserver);
  86907. }
  86908. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86909. },
  86910. enumerable: true,
  86911. configurable: true
  86912. });
  86913. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86914. set: function (callback) {
  86915. if (this._onBeforeRenderObserver) {
  86916. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86917. }
  86918. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86919. },
  86920. enumerable: true,
  86921. configurable: true
  86922. });
  86923. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86924. set: function (callback) {
  86925. if (this._onAfterRenderObserver) {
  86926. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86927. }
  86928. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86929. },
  86930. enumerable: true,
  86931. configurable: true
  86932. });
  86933. Layer.prototype._createIndexBuffer = function () {
  86934. var engine = this._scene.getEngine();
  86935. // Indices
  86936. var indices = [];
  86937. indices.push(0);
  86938. indices.push(1);
  86939. indices.push(2);
  86940. indices.push(0);
  86941. indices.push(2);
  86942. indices.push(3);
  86943. this._indexBuffer = engine.createIndexBuffer(indices);
  86944. };
  86945. Layer.prototype._rebuild = function () {
  86946. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86947. if (vb) {
  86948. vb._rebuild();
  86949. }
  86950. this._createIndexBuffer();
  86951. };
  86952. Layer.prototype.render = function () {
  86953. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86954. // Check
  86955. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86956. return;
  86957. var engine = this._scene.getEngine();
  86958. this.onBeforeRenderObservable.notifyObservers(this);
  86959. // Render
  86960. engine.enableEffect(currentEffect);
  86961. engine.setState(false);
  86962. // Texture
  86963. currentEffect.setTexture("textureSampler", this.texture);
  86964. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86965. // Color
  86966. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86967. // Scale / offset
  86968. currentEffect.setVector2("offset", this.offset);
  86969. currentEffect.setVector2("scale", this.scale);
  86970. // VBOs
  86971. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86972. // Draw order
  86973. if (!this.alphaTest) {
  86974. engine.setAlphaMode(this.alphaBlendingMode);
  86975. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86976. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86977. }
  86978. else {
  86979. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86980. }
  86981. this.onAfterRenderObservable.notifyObservers(this);
  86982. };
  86983. Layer.prototype.dispose = function () {
  86984. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86985. if (vertexBuffer) {
  86986. vertexBuffer.dispose();
  86987. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86988. }
  86989. if (this._indexBuffer) {
  86990. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86991. this._indexBuffer = null;
  86992. }
  86993. if (this.texture) {
  86994. this.texture.dispose();
  86995. this.texture = null;
  86996. }
  86997. // Remove from scene
  86998. var index = this._scene.layers.indexOf(this);
  86999. this._scene.layers.splice(index, 1);
  87000. // Callback
  87001. this.onDisposeObservable.notifyObservers(this);
  87002. this.onDisposeObservable.clear();
  87003. this.onAfterRenderObservable.clear();
  87004. this.onBeforeRenderObservable.clear();
  87005. };
  87006. return Layer;
  87007. }());
  87008. BABYLON.Layer = Layer;
  87009. })(BABYLON || (BABYLON = {}));
  87010. //# sourceMappingURL=babylon.layer.js.map
  87011. var BABYLON;
  87012. (function (BABYLON) {
  87013. var TextureTools = /** @class */ (function () {
  87014. function TextureTools() {
  87015. }
  87016. /**
  87017. * Uses the GPU to create a copy texture rescaled at a given size
  87018. * @param texture Texture to copy from
  87019. * @param width Desired width
  87020. * @param height Desired height
  87021. * @return Generated texture
  87022. */
  87023. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87024. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87025. var scene = texture.getScene();
  87026. var engine = scene.getEngine();
  87027. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87028. rtt.wrapU = texture.wrapU;
  87029. rtt.wrapV = texture.wrapV;
  87030. rtt.uOffset = texture.uOffset;
  87031. rtt.vOffset = texture.vOffset;
  87032. rtt.uScale = texture.uScale;
  87033. rtt.vScale = texture.vScale;
  87034. rtt.uAng = texture.uAng;
  87035. rtt.vAng = texture.vAng;
  87036. rtt.wAng = texture.wAng;
  87037. rtt.coordinatesIndex = texture.coordinatesIndex;
  87038. rtt.level = texture.level;
  87039. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87040. rtt._texture.isReady = false;
  87041. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87042. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87043. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87044. passPostProcess.getEffect().executeWhenCompiled(function () {
  87045. passPostProcess.onApply = function (effect) {
  87046. effect.setTexture("textureSampler", texture);
  87047. };
  87048. var internalTexture = rtt.getInternalTexture();
  87049. if (internalTexture) {
  87050. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87051. engine.unBindFramebuffer(internalTexture);
  87052. rtt.disposeFramebufferObjects();
  87053. passPostProcess.dispose();
  87054. internalTexture.isReady = true;
  87055. }
  87056. });
  87057. return rtt;
  87058. };
  87059. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87060. if (!scene._environmentBRDFTexture) {
  87061. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87062. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87063. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87064. scene._environmentBRDFTexture = texture;
  87065. }
  87066. return scene._environmentBRDFTexture;
  87067. };
  87068. 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=";
  87069. return TextureTools;
  87070. }());
  87071. BABYLON.TextureTools = TextureTools;
  87072. })(BABYLON || (BABYLON = {}));
  87073. //# sourceMappingURL=babylon.textureTools.js.map
  87074. var BABYLON;
  87075. (function (BABYLON) {
  87076. var FramingBehavior = /** @class */ (function () {
  87077. function FramingBehavior() {
  87078. this._mode = FramingBehavior.FitFrustumSidesMode;
  87079. this._radiusScale = 1.0;
  87080. this._positionScale = 0.5;
  87081. this._defaultElevation = 0.3;
  87082. this._elevationReturnTime = 1500;
  87083. this._elevationReturnWaitTime = 1000;
  87084. this._zoomStopsAnimation = false;
  87085. this._framingTime = 1500;
  87086. this._isPointerDown = false;
  87087. this._lastInteractionTime = -Infinity;
  87088. // Framing control
  87089. this._animatables = new Array();
  87090. this._betaIsAnimating = false;
  87091. }
  87092. Object.defineProperty(FramingBehavior.prototype, "name", {
  87093. get: function () {
  87094. return "Framing";
  87095. },
  87096. enumerable: true,
  87097. configurable: true
  87098. });
  87099. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87100. /**
  87101. * Gets current mode used by the behavior.
  87102. */
  87103. get: function () {
  87104. return this._mode;
  87105. },
  87106. /**
  87107. * Sets the current mode used by the behavior
  87108. */
  87109. set: function (mode) {
  87110. this._mode = mode;
  87111. },
  87112. enumerable: true,
  87113. configurable: true
  87114. });
  87115. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87116. /**
  87117. * Gets the scale applied to the radius
  87118. */
  87119. get: function () {
  87120. return this._radiusScale;
  87121. },
  87122. /**
  87123. * Sets the scale applied to the radius (1 by default)
  87124. */
  87125. set: function (radius) {
  87126. this._radiusScale = radius;
  87127. },
  87128. enumerable: true,
  87129. configurable: true
  87130. });
  87131. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87132. /**
  87133. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87134. */
  87135. get: function () {
  87136. return this._positionScale;
  87137. },
  87138. /**
  87139. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87140. */
  87141. set: function (scale) {
  87142. this._positionScale = scale;
  87143. },
  87144. enumerable: true,
  87145. configurable: true
  87146. });
  87147. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87148. /**
  87149. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87150. * behaviour is triggered, in radians.
  87151. */
  87152. get: function () {
  87153. return this._defaultElevation;
  87154. },
  87155. /**
  87156. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87157. * behaviour is triggered, in radians.
  87158. */
  87159. set: function (elevation) {
  87160. this._defaultElevation = elevation;
  87161. },
  87162. enumerable: true,
  87163. configurable: true
  87164. });
  87165. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87166. /**
  87167. * Gets the time (in milliseconds) taken to return to the default beta position.
  87168. * Negative value indicates camera should not return to default.
  87169. */
  87170. get: function () {
  87171. return this._elevationReturnTime;
  87172. },
  87173. /**
  87174. * Sets the time (in milliseconds) taken to return to the default beta position.
  87175. * Negative value indicates camera should not return to default.
  87176. */
  87177. set: function (speed) {
  87178. this._elevationReturnTime = speed;
  87179. },
  87180. enumerable: true,
  87181. configurable: true
  87182. });
  87183. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87184. /**
  87185. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87186. */
  87187. get: function () {
  87188. return this._elevationReturnWaitTime;
  87189. },
  87190. /**
  87191. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87192. */
  87193. set: function (time) {
  87194. this._elevationReturnWaitTime = time;
  87195. },
  87196. enumerable: true,
  87197. configurable: true
  87198. });
  87199. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87200. /**
  87201. * Gets the flag that indicates if user zooming should stop animation.
  87202. */
  87203. get: function () {
  87204. return this._zoomStopsAnimation;
  87205. },
  87206. /**
  87207. * Sets the flag that indicates if user zooming should stop animation.
  87208. */
  87209. set: function (flag) {
  87210. this._zoomStopsAnimation = flag;
  87211. },
  87212. enumerable: true,
  87213. configurable: true
  87214. });
  87215. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87216. /**
  87217. * Gets the transition time when framing the mesh, in milliseconds
  87218. */
  87219. get: function () {
  87220. return this._framingTime;
  87221. },
  87222. /**
  87223. * Sets the transition time when framing the mesh, in milliseconds
  87224. */
  87225. set: function (time) {
  87226. this._framingTime = time;
  87227. },
  87228. enumerable: true,
  87229. configurable: true
  87230. });
  87231. FramingBehavior.prototype.init = function () {
  87232. // Do notihng
  87233. };
  87234. FramingBehavior.prototype.attach = function (camera) {
  87235. var _this = this;
  87236. this._attachedCamera = camera;
  87237. var scene = this._attachedCamera.getScene();
  87238. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87239. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87240. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87241. _this._isPointerDown = true;
  87242. return;
  87243. }
  87244. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87245. _this._isPointerDown = false;
  87246. }
  87247. });
  87248. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87249. if (mesh) {
  87250. _this.zoomOnMesh(mesh);
  87251. }
  87252. });
  87253. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87254. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87255. _this._applyUserInteraction();
  87256. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87257. // back to the default position after a given timeout
  87258. _this._maintainCameraAboveGround();
  87259. });
  87260. };
  87261. FramingBehavior.prototype.detach = function () {
  87262. if (!this._attachedCamera) {
  87263. return;
  87264. }
  87265. var scene = this._attachedCamera.getScene();
  87266. if (this._onPrePointerObservableObserver) {
  87267. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87268. }
  87269. if (this._onAfterCheckInputsObserver) {
  87270. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87271. }
  87272. if (this._onMeshTargetChangedObserver) {
  87273. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87274. }
  87275. this._attachedCamera = null;
  87276. };
  87277. /**
  87278. * Targets the given mesh and updates zoom level accordingly.
  87279. * @param mesh The mesh to target.
  87280. * @param radius Optional. If a cached radius position already exists, overrides default.
  87281. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87282. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87283. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87284. */
  87285. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87286. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87287. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87288. mesh.computeWorldMatrix(true);
  87289. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87290. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87291. };
  87292. /**
  87293. * Targets the given mesh with its children and updates zoom level accordingly.
  87294. * @param mesh The mesh to target.
  87295. * @param radius Optional. If a cached radius position already exists, overrides default.
  87296. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87297. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87298. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87299. */
  87300. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87301. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87302. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87303. mesh.computeWorldMatrix(true);
  87304. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87305. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87306. };
  87307. /**
  87308. * Targets the given meshes with their children and updates zoom level accordingly.
  87309. * @param meshes The mesh to target.
  87310. * @param radius Optional. If a cached radius position already exists, overrides default.
  87311. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87312. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87313. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87314. */
  87315. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87316. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87317. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87318. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87319. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87320. for (var i = 0; i < meshes.length; i++) {
  87321. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87322. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87323. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87324. }
  87325. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87326. };
  87327. /**
  87328. * Targets the given mesh and updates zoom level accordingly.
  87329. * @param mesh The mesh to target.
  87330. * @param radius Optional. If a cached radius position already exists, overrides default.
  87331. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87332. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87333. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87334. */
  87335. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87336. var _this = this;
  87337. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87338. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87339. var zoomTarget;
  87340. if (!this._attachedCamera) {
  87341. return;
  87342. }
  87343. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87344. var bottom = minimumWorld.y;
  87345. var top = maximumWorld.y;
  87346. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87347. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87348. if (focusOnOriginXZ) {
  87349. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87350. }
  87351. else {
  87352. var centerWorld = minimumWorld.add(radiusWorld);
  87353. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87354. }
  87355. if (!this._vectorTransition) {
  87356. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87357. }
  87358. this._betaIsAnimating = true;
  87359. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87360. if (animatable) {
  87361. this._animatables.push(animatable);
  87362. }
  87363. // sets the radius and lower radius bounds
  87364. // Small delta ensures camera is not always at lower zoom limit.
  87365. var radius = 0;
  87366. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87367. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87368. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87369. radius = position;
  87370. }
  87371. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87372. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87373. if (this._attachedCamera.lowerRadiusLimit === null) {
  87374. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87375. }
  87376. }
  87377. // Set sensibilities
  87378. var extend = maximumWorld.subtract(minimumWorld).length();
  87379. this._attachedCamera.panningSensibility = 5000 / extend;
  87380. this._attachedCamera.wheelPrecision = 100 / radius;
  87381. // transition to new radius
  87382. if (!this._radiusTransition) {
  87383. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87384. }
  87385. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87386. _this.stopAllAnimations();
  87387. if (onAnimationEnd) {
  87388. onAnimationEnd();
  87389. }
  87390. if (_this._attachedCamera) {
  87391. _this._attachedCamera.storeState();
  87392. }
  87393. });
  87394. if (animatable) {
  87395. this._animatables.push(animatable);
  87396. }
  87397. };
  87398. /**
  87399. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87400. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87401. * frustum width.
  87402. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87403. * to fully enclose the mesh in the viewing frustum.
  87404. */
  87405. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87406. var size = maximumWorld.subtract(minimumWorld);
  87407. var boxVectorGlobalDiagonal = size.length();
  87408. var frustumSlope = this._getFrustumSlope();
  87409. // Formula for setting distance
  87410. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87411. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87412. // Horizon distance
  87413. var radius = radiusWithoutFraming * this._radiusScale;
  87414. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87415. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87416. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87417. var camera = this._attachedCamera;
  87418. if (!camera) {
  87419. return 0;
  87420. }
  87421. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87422. // Don't exceed the requested limit
  87423. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87424. }
  87425. // Don't exceed the upper radius limit
  87426. if (camera.upperRadiusLimit) {
  87427. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87428. }
  87429. return distance;
  87430. };
  87431. /**
  87432. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87433. * is automatically returned to its default position (expected to be above ground plane).
  87434. */
  87435. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87436. var _this = this;
  87437. if (this._elevationReturnTime < 0) {
  87438. return;
  87439. }
  87440. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87441. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87442. var limitBeta = Math.PI * 0.5;
  87443. // Bring the camera back up if below the ground plane
  87444. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87445. this._betaIsAnimating = true;
  87446. //Transition to new position
  87447. this.stopAllAnimations();
  87448. if (!this._betaTransition) {
  87449. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87450. }
  87451. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87452. _this._clearAnimationLocks();
  87453. _this.stopAllAnimations();
  87454. });
  87455. if (animatabe) {
  87456. this._animatables.push(animatabe);
  87457. }
  87458. }
  87459. };
  87460. /**
  87461. * Returns the frustum slope based on the canvas ratio and camera FOV
  87462. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87463. */
  87464. FramingBehavior.prototype._getFrustumSlope = function () {
  87465. // Calculate the viewport ratio
  87466. // Aspect Ratio is Height/Width.
  87467. var camera = this._attachedCamera;
  87468. if (!camera) {
  87469. return BABYLON.Vector2.Zero();
  87470. }
  87471. var engine = camera.getScene().getEngine();
  87472. var aspectRatio = engine.getAspectRatio(camera);
  87473. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87474. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87475. var frustumSlopeY = Math.tan(camera.fov / 2);
  87476. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87477. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87478. // along the forward vector.
  87479. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87480. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87481. };
  87482. /**
  87483. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87484. */
  87485. FramingBehavior.prototype._clearAnimationLocks = function () {
  87486. this._betaIsAnimating = false;
  87487. };
  87488. /**
  87489. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87490. */
  87491. FramingBehavior.prototype._applyUserInteraction = function () {
  87492. if (this.isUserIsMoving) {
  87493. this._lastInteractionTime = BABYLON.Tools.Now;
  87494. this.stopAllAnimations();
  87495. this._clearAnimationLocks();
  87496. }
  87497. };
  87498. /**
  87499. * Stops and removes all animations that have been applied to the camera
  87500. */
  87501. FramingBehavior.prototype.stopAllAnimations = function () {
  87502. if (this._attachedCamera) {
  87503. this._attachedCamera.animations = [];
  87504. }
  87505. while (this._animatables.length) {
  87506. if (this._animatables[0]) {
  87507. this._animatables[0].onAnimationEnd = null;
  87508. this._animatables[0].stop();
  87509. }
  87510. this._animatables.shift();
  87511. }
  87512. };
  87513. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87514. /**
  87515. * Gets a value indicating if the user is moving the camera
  87516. */
  87517. get: function () {
  87518. if (!this._attachedCamera) {
  87519. return false;
  87520. }
  87521. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87522. this._attachedCamera.inertialBetaOffset !== 0 ||
  87523. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87524. this._attachedCamera.inertialPanningX !== 0 ||
  87525. this._attachedCamera.inertialPanningY !== 0 ||
  87526. this._isPointerDown;
  87527. },
  87528. enumerable: true,
  87529. configurable: true
  87530. });
  87531. /**
  87532. * The easing function used by animations
  87533. */
  87534. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87535. /**
  87536. * The easing mode used by animations
  87537. */
  87538. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87539. // Statics
  87540. /**
  87541. * The camera can move all the way towards the mesh.
  87542. */
  87543. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87544. /**
  87545. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87546. */
  87547. FramingBehavior.FitFrustumSidesMode = 1;
  87548. return FramingBehavior;
  87549. }());
  87550. BABYLON.FramingBehavior = FramingBehavior;
  87551. })(BABYLON || (BABYLON = {}));
  87552. //# sourceMappingURL=babylon.framingBehavior.js.map
  87553. var BABYLON;
  87554. (function (BABYLON) {
  87555. /**
  87556. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87557. */
  87558. var BouncingBehavior = /** @class */ (function () {
  87559. function BouncingBehavior() {
  87560. /**
  87561. * The duration of the animation, in milliseconds
  87562. */
  87563. this.transitionDuration = 450;
  87564. /**
  87565. * Length of the distance animated by the transition when lower radius is reached
  87566. */
  87567. this.lowerRadiusTransitionRange = 2;
  87568. /**
  87569. * Length of the distance animated by the transition when upper radius is reached
  87570. */
  87571. this.upperRadiusTransitionRange = -2;
  87572. this._autoTransitionRange = false;
  87573. // Animations
  87574. this._radiusIsAnimating = false;
  87575. this._radiusBounceTransition = null;
  87576. this._animatables = new Array();
  87577. }
  87578. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87579. get: function () {
  87580. return "Bouncing";
  87581. },
  87582. enumerable: true,
  87583. configurable: true
  87584. });
  87585. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87586. /**
  87587. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87588. */
  87589. get: function () {
  87590. return this._autoTransitionRange;
  87591. },
  87592. /**
  87593. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87594. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87595. */
  87596. set: function (value) {
  87597. var _this = this;
  87598. if (this._autoTransitionRange === value) {
  87599. return;
  87600. }
  87601. this._autoTransitionRange = value;
  87602. var camera = this._attachedCamera;
  87603. if (!camera) {
  87604. return;
  87605. }
  87606. if (value) {
  87607. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87608. if (!mesh) {
  87609. return;
  87610. }
  87611. mesh.computeWorldMatrix(true);
  87612. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87613. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87614. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87615. });
  87616. }
  87617. else if (this._onMeshTargetChangedObserver) {
  87618. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87619. }
  87620. },
  87621. enumerable: true,
  87622. configurable: true
  87623. });
  87624. BouncingBehavior.prototype.init = function () {
  87625. // Do notihng
  87626. };
  87627. BouncingBehavior.prototype.attach = function (camera) {
  87628. var _this = this;
  87629. this._attachedCamera = camera;
  87630. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87631. if (!_this._attachedCamera) {
  87632. return;
  87633. }
  87634. // Add the bounce animation to the lower radius limit
  87635. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87636. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87637. }
  87638. // Add the bounce animation to the upper radius limit
  87639. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87640. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87641. }
  87642. });
  87643. };
  87644. BouncingBehavior.prototype.detach = function () {
  87645. if (!this._attachedCamera) {
  87646. return;
  87647. }
  87648. if (this._onAfterCheckInputsObserver) {
  87649. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87650. }
  87651. if (this._onMeshTargetChangedObserver) {
  87652. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87653. }
  87654. this._attachedCamera = null;
  87655. };
  87656. /**
  87657. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87658. * @param radiusLimit The limit to check against.
  87659. * @return Bool to indicate if at limit.
  87660. */
  87661. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87662. if (!this._attachedCamera) {
  87663. return false;
  87664. }
  87665. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87666. return true;
  87667. }
  87668. return false;
  87669. };
  87670. /**
  87671. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87672. * @param radiusDelta The delta by which to animate to. Can be negative.
  87673. */
  87674. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87675. var _this = this;
  87676. if (!this._attachedCamera) {
  87677. return;
  87678. }
  87679. if (!this._radiusBounceTransition) {
  87680. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87681. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87682. }
  87683. // Prevent zoom until bounce has completed
  87684. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87685. this._attachedCamera.wheelPrecision = Infinity;
  87686. this._attachedCamera.inertialRadiusOffset = 0;
  87687. // Animate to the radius limit
  87688. this.stopAllAnimations();
  87689. this._radiusIsAnimating = true;
  87690. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87691. if (animatable) {
  87692. this._animatables.push(animatable);
  87693. }
  87694. };
  87695. /**
  87696. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87697. */
  87698. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87699. this._radiusIsAnimating = false;
  87700. if (this._attachedCamera) {
  87701. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87702. }
  87703. };
  87704. /**
  87705. * Stops and removes all animations that have been applied to the camera
  87706. */
  87707. BouncingBehavior.prototype.stopAllAnimations = function () {
  87708. if (this._attachedCamera) {
  87709. this._attachedCamera.animations = [];
  87710. }
  87711. while (this._animatables.length) {
  87712. this._animatables[0].onAnimationEnd = null;
  87713. this._animatables[0].stop();
  87714. this._animatables.shift();
  87715. }
  87716. };
  87717. /**
  87718. * The easing function used by animations
  87719. */
  87720. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87721. /**
  87722. * The easing mode used by animations
  87723. */
  87724. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87725. return BouncingBehavior;
  87726. }());
  87727. BABYLON.BouncingBehavior = BouncingBehavior;
  87728. })(BABYLON || (BABYLON = {}));
  87729. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87730. var BABYLON;
  87731. (function (BABYLON) {
  87732. var AutoRotationBehavior = /** @class */ (function () {
  87733. function AutoRotationBehavior() {
  87734. this._zoomStopsAnimation = false;
  87735. this._idleRotationSpeed = 0.05;
  87736. this._idleRotationWaitTime = 2000;
  87737. this._idleRotationSpinupTime = 2000;
  87738. this._isPointerDown = false;
  87739. this._lastFrameTime = null;
  87740. this._lastInteractionTime = -Infinity;
  87741. this._cameraRotationSpeed = 0;
  87742. this._lastFrameRadius = 0;
  87743. }
  87744. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87745. get: function () {
  87746. return "AutoRotation";
  87747. },
  87748. enumerable: true,
  87749. configurable: true
  87750. });
  87751. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87752. /**
  87753. * Gets the flag that indicates if user zooming should stop animation.
  87754. */
  87755. get: function () {
  87756. return this._zoomStopsAnimation;
  87757. },
  87758. /**
  87759. * Sets the flag that indicates if user zooming should stop animation.
  87760. */
  87761. set: function (flag) {
  87762. this._zoomStopsAnimation = flag;
  87763. },
  87764. enumerable: true,
  87765. configurable: true
  87766. });
  87767. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87768. /**
  87769. * Gets the default speed at which the camera rotates around the model.
  87770. */
  87771. get: function () {
  87772. return this._idleRotationSpeed;
  87773. },
  87774. /**
  87775. * Sets the default speed at which the camera rotates around the model.
  87776. */
  87777. set: function (speed) {
  87778. this._idleRotationSpeed = speed;
  87779. },
  87780. enumerable: true,
  87781. configurable: true
  87782. });
  87783. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87784. /**
  87785. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87786. */
  87787. get: function () {
  87788. return this._idleRotationWaitTime;
  87789. },
  87790. /**
  87791. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87792. */
  87793. set: function (time) {
  87794. this._idleRotationWaitTime = time;
  87795. },
  87796. enumerable: true,
  87797. configurable: true
  87798. });
  87799. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87800. /**
  87801. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87802. */
  87803. get: function () {
  87804. return this._idleRotationSpinupTime;
  87805. },
  87806. /**
  87807. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87808. */
  87809. set: function (time) {
  87810. this._idleRotationSpinupTime = time;
  87811. },
  87812. enumerable: true,
  87813. configurable: true
  87814. });
  87815. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87816. /**
  87817. * Gets a value indicating if the camera is currently rotating because of this behavior
  87818. */
  87819. get: function () {
  87820. return Math.abs(this._cameraRotationSpeed) > 0;
  87821. },
  87822. enumerable: true,
  87823. configurable: true
  87824. });
  87825. AutoRotationBehavior.prototype.init = function () {
  87826. // Do notihng
  87827. };
  87828. AutoRotationBehavior.prototype.attach = function (camera) {
  87829. var _this = this;
  87830. this._attachedCamera = camera;
  87831. var scene = this._attachedCamera.getScene();
  87832. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87833. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87834. _this._isPointerDown = true;
  87835. return;
  87836. }
  87837. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87838. _this._isPointerDown = false;
  87839. }
  87840. });
  87841. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87842. var now = BABYLON.Tools.Now;
  87843. var dt = 0;
  87844. if (_this._lastFrameTime != null) {
  87845. dt = now - _this._lastFrameTime;
  87846. }
  87847. _this._lastFrameTime = now;
  87848. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87849. _this._applyUserInteraction();
  87850. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87851. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87852. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87853. // Step camera rotation by rotation speed
  87854. if (_this._attachedCamera) {
  87855. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87856. }
  87857. });
  87858. };
  87859. AutoRotationBehavior.prototype.detach = function () {
  87860. if (!this._attachedCamera) {
  87861. return;
  87862. }
  87863. var scene = this._attachedCamera.getScene();
  87864. if (this._onPrePointerObservableObserver) {
  87865. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87866. }
  87867. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87868. this._attachedCamera = null;
  87869. };
  87870. /**
  87871. * Returns true if user is scrolling.
  87872. * @return true if user is scrolling.
  87873. */
  87874. AutoRotationBehavior.prototype._userIsZooming = function () {
  87875. if (!this._attachedCamera) {
  87876. return false;
  87877. }
  87878. return this._attachedCamera.inertialRadiusOffset !== 0;
  87879. };
  87880. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87881. if (!this._attachedCamera) {
  87882. return false;
  87883. }
  87884. var zoomHasHitLimit = false;
  87885. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87886. zoomHasHitLimit = true;
  87887. }
  87888. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87889. this._lastFrameRadius = this._attachedCamera.radius;
  87890. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87891. };
  87892. /**
  87893. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87894. */
  87895. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87896. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87897. this._lastInteractionTime = BABYLON.Tools.Now;
  87898. }
  87899. };
  87900. // Tools
  87901. AutoRotationBehavior.prototype._userIsMoving = function () {
  87902. if (!this._attachedCamera) {
  87903. return false;
  87904. }
  87905. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87906. this._attachedCamera.inertialBetaOffset !== 0 ||
  87907. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87908. this._attachedCamera.inertialPanningX !== 0 ||
  87909. this._attachedCamera.inertialPanningY !== 0 ||
  87910. this._isPointerDown;
  87911. };
  87912. return AutoRotationBehavior;
  87913. }());
  87914. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87915. })(BABYLON || (BABYLON = {}));
  87916. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87917. var BABYLON;
  87918. (function (BABYLON) {
  87919. /**
  87920. * This class can be used to get instrumentation data from a Babylon engine
  87921. */
  87922. var EngineInstrumentation = /** @class */ (function () {
  87923. function EngineInstrumentation(engine) {
  87924. this.engine = engine;
  87925. this._captureGPUFrameTime = false;
  87926. this._gpuFrameTime = new BABYLON.PerfCounter();
  87927. this._captureShaderCompilationTime = false;
  87928. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87929. // Observers
  87930. this._onBeginFrameObserver = null;
  87931. this._onEndFrameObserver = null;
  87932. this._onBeforeShaderCompilationObserver = null;
  87933. this._onAfterShaderCompilationObserver = null;
  87934. }
  87935. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87936. // Properties
  87937. /**
  87938. * Gets the perf counter used for GPU frame time
  87939. */
  87940. get: function () {
  87941. return this._gpuFrameTime;
  87942. },
  87943. enumerable: true,
  87944. configurable: true
  87945. });
  87946. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87947. /**
  87948. * Gets the GPU frame time capture status
  87949. */
  87950. get: function () {
  87951. return this._captureGPUFrameTime;
  87952. },
  87953. /**
  87954. * Enable or disable the GPU frame time capture
  87955. */
  87956. set: function (value) {
  87957. var _this = this;
  87958. if (value === this._captureGPUFrameTime) {
  87959. return;
  87960. }
  87961. this._captureGPUFrameTime = value;
  87962. if (value) {
  87963. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87964. if (!_this._gpuFrameTimeToken) {
  87965. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87966. }
  87967. });
  87968. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87969. if (!_this._gpuFrameTimeToken) {
  87970. return;
  87971. }
  87972. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87973. if (time > -1) {
  87974. _this._gpuFrameTimeToken = null;
  87975. _this._gpuFrameTime.fetchNewFrame();
  87976. _this._gpuFrameTime.addCount(time, true);
  87977. }
  87978. });
  87979. }
  87980. else {
  87981. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87982. this._onBeginFrameObserver = null;
  87983. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87984. this._onEndFrameObserver = null;
  87985. }
  87986. },
  87987. enumerable: true,
  87988. configurable: true
  87989. });
  87990. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87991. /**
  87992. * Gets the perf counter used for shader compilation time
  87993. */
  87994. get: function () {
  87995. return this._shaderCompilationTime;
  87996. },
  87997. enumerable: true,
  87998. configurable: true
  87999. });
  88000. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  88001. /**
  88002. * Gets the shader compilation time capture status
  88003. */
  88004. get: function () {
  88005. return this._captureShaderCompilationTime;
  88006. },
  88007. /**
  88008. * Enable or disable the shader compilation time capture
  88009. */
  88010. set: function (value) {
  88011. var _this = this;
  88012. if (value === this._captureShaderCompilationTime) {
  88013. return;
  88014. }
  88015. this._captureShaderCompilationTime = value;
  88016. if (value) {
  88017. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88018. _this._shaderCompilationTime.fetchNewFrame();
  88019. _this._shaderCompilationTime.beginMonitoring();
  88020. });
  88021. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88022. _this._shaderCompilationTime.endMonitoring();
  88023. });
  88024. }
  88025. else {
  88026. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88027. this._onBeforeShaderCompilationObserver = null;
  88028. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88029. this._onAfterShaderCompilationObserver = null;
  88030. }
  88031. },
  88032. enumerable: true,
  88033. configurable: true
  88034. });
  88035. EngineInstrumentation.prototype.dispose = function () {
  88036. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88037. this._onBeginFrameObserver = null;
  88038. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88039. this._onEndFrameObserver = null;
  88040. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88041. this._onBeforeShaderCompilationObserver = null;
  88042. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88043. this._onAfterShaderCompilationObserver = null;
  88044. this.engine = null;
  88045. };
  88046. return EngineInstrumentation;
  88047. }());
  88048. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88049. })(BABYLON || (BABYLON = {}));
  88050. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88051. var BABYLON;
  88052. (function (BABYLON) {
  88053. /**
  88054. * This class can be used to get instrumentation data from a Babylon engine
  88055. */
  88056. var SceneInstrumentation = /** @class */ (function () {
  88057. function SceneInstrumentation(scene) {
  88058. var _this = this;
  88059. this.scene = scene;
  88060. this._captureActiveMeshesEvaluationTime = false;
  88061. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88062. this._captureRenderTargetsRenderTime = false;
  88063. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88064. this._captureFrameTime = false;
  88065. this._frameTime = new BABYLON.PerfCounter();
  88066. this._captureRenderTime = false;
  88067. this._renderTime = new BABYLON.PerfCounter();
  88068. this._captureInterFrameTime = false;
  88069. this._interFrameTime = new BABYLON.PerfCounter();
  88070. this._captureParticlesRenderTime = false;
  88071. this._particlesRenderTime = new BABYLON.PerfCounter();
  88072. this._captureSpritesRenderTime = false;
  88073. this._spritesRenderTime = new BABYLON.PerfCounter();
  88074. this._capturePhysicsTime = false;
  88075. this._physicsTime = new BABYLON.PerfCounter();
  88076. this._captureAnimationsTime = false;
  88077. this._animationsTime = new BABYLON.PerfCounter();
  88078. // Observers
  88079. this._onBeforeActiveMeshesEvaluationObserver = null;
  88080. this._onAfterActiveMeshesEvaluationObserver = null;
  88081. this._onBeforeRenderTargetsRenderObserver = null;
  88082. this._onAfterRenderTargetsRenderObserver = null;
  88083. this._onAfterRenderObserver = null;
  88084. this._onBeforeDrawPhaseObserver = null;
  88085. this._onAfterDrawPhaseObserver = null;
  88086. this._onBeforeAnimationsObserver = null;
  88087. this._onBeforeParticlesRenderingObserver = null;
  88088. this._onAfterParticlesRenderingObserver = null;
  88089. this._onBeforeSpritesRenderingObserver = null;
  88090. this._onAfterSpritesRenderingObserver = null;
  88091. this._onBeforePhysicsObserver = null;
  88092. this._onAfterPhysicsObserver = null;
  88093. this._onAfterAnimationsObserver = null;
  88094. // Before render
  88095. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88096. if (_this._captureActiveMeshesEvaluationTime) {
  88097. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88098. }
  88099. if (_this._captureRenderTargetsRenderTime) {
  88100. _this._renderTargetsRenderTime.fetchNewFrame();
  88101. }
  88102. if (_this._captureFrameTime) {
  88103. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88104. _this._frameTime.beginMonitoring();
  88105. }
  88106. if (_this._captureInterFrameTime) {
  88107. _this._interFrameTime.endMonitoring();
  88108. }
  88109. if (_this._captureParticlesRenderTime) {
  88110. _this._particlesRenderTime.fetchNewFrame();
  88111. }
  88112. if (_this._captureSpritesRenderTime) {
  88113. _this._spritesRenderTime.fetchNewFrame();
  88114. }
  88115. if (_this._captureAnimationsTime) {
  88116. _this._animationsTime.beginMonitoring();
  88117. }
  88118. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88119. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88120. });
  88121. // After render
  88122. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88123. if (_this._captureFrameTime) {
  88124. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88125. _this._frameTime.endMonitoring();
  88126. }
  88127. if (_this._captureRenderTime) {
  88128. _this._renderTime.endMonitoring(false);
  88129. }
  88130. if (_this._captureInterFrameTime) {
  88131. _this._interFrameTime.beginMonitoring();
  88132. }
  88133. });
  88134. }
  88135. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88136. // Properties
  88137. /**
  88138. * Gets the perf counter used for active meshes evaluation time
  88139. */
  88140. get: function () {
  88141. return this._activeMeshesEvaluationTime;
  88142. },
  88143. enumerable: true,
  88144. configurable: true
  88145. });
  88146. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88147. /**
  88148. * Gets the active meshes evaluation time capture status
  88149. */
  88150. get: function () {
  88151. return this._captureActiveMeshesEvaluationTime;
  88152. },
  88153. /**
  88154. * Enable or disable the active meshes evaluation time capture
  88155. */
  88156. set: function (value) {
  88157. var _this = this;
  88158. if (value === this._captureActiveMeshesEvaluationTime) {
  88159. return;
  88160. }
  88161. this._captureActiveMeshesEvaluationTime = value;
  88162. if (value) {
  88163. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88164. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88165. _this._activeMeshesEvaluationTime.beginMonitoring();
  88166. });
  88167. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88168. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88169. _this._activeMeshesEvaluationTime.endMonitoring();
  88170. });
  88171. }
  88172. else {
  88173. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88174. this._onBeforeActiveMeshesEvaluationObserver = null;
  88175. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88176. this._onAfterActiveMeshesEvaluationObserver = null;
  88177. }
  88178. },
  88179. enumerable: true,
  88180. configurable: true
  88181. });
  88182. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88183. /**
  88184. * Gets the perf counter used for render targets render time
  88185. */
  88186. get: function () {
  88187. return this._renderTargetsRenderTime;
  88188. },
  88189. enumerable: true,
  88190. configurable: true
  88191. });
  88192. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88193. /**
  88194. * Gets the render targets render time capture status
  88195. */
  88196. get: function () {
  88197. return this._captureRenderTargetsRenderTime;
  88198. },
  88199. /**
  88200. * Enable or disable the render targets render time capture
  88201. */
  88202. set: function (value) {
  88203. var _this = this;
  88204. if (value === this._captureRenderTargetsRenderTime) {
  88205. return;
  88206. }
  88207. this._captureRenderTargetsRenderTime = value;
  88208. if (value) {
  88209. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88210. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88211. _this._renderTargetsRenderTime.beginMonitoring();
  88212. });
  88213. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88214. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88215. _this._renderTargetsRenderTime.endMonitoring(false);
  88216. });
  88217. }
  88218. else {
  88219. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88220. this._onBeforeRenderTargetsRenderObserver = null;
  88221. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88222. this._onAfterRenderTargetsRenderObserver = null;
  88223. }
  88224. },
  88225. enumerable: true,
  88226. configurable: true
  88227. });
  88228. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  88229. /**
  88230. * Gets the perf counter used for particles render time
  88231. */
  88232. get: function () {
  88233. return this._particlesRenderTime;
  88234. },
  88235. enumerable: true,
  88236. configurable: true
  88237. });
  88238. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  88239. /**
  88240. * Gets the particles render time capture status
  88241. */
  88242. get: function () {
  88243. return this._captureParticlesRenderTime;
  88244. },
  88245. /**
  88246. * Enable or disable the particles render time capture
  88247. */
  88248. set: function (value) {
  88249. var _this = this;
  88250. if (value === this._captureParticlesRenderTime) {
  88251. return;
  88252. }
  88253. this._captureParticlesRenderTime = value;
  88254. if (value) {
  88255. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88256. BABYLON.Tools.StartPerformanceCounter("Particles");
  88257. _this._particlesRenderTime.beginMonitoring();
  88258. });
  88259. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88260. BABYLON.Tools.EndPerformanceCounter("Particles");
  88261. _this._particlesRenderTime.endMonitoring(false);
  88262. });
  88263. }
  88264. else {
  88265. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88266. this._onBeforeParticlesRenderingObserver = null;
  88267. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88268. this._onAfterParticlesRenderingObserver = null;
  88269. }
  88270. },
  88271. enumerable: true,
  88272. configurable: true
  88273. });
  88274. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88275. /**
  88276. * Gets the perf counter used for sprites render time
  88277. */
  88278. get: function () {
  88279. return this._spritesRenderTime;
  88280. },
  88281. enumerable: true,
  88282. configurable: true
  88283. });
  88284. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88285. /**
  88286. * Gets the sprites render time capture status
  88287. */
  88288. get: function () {
  88289. return this._captureSpritesRenderTime;
  88290. },
  88291. /**
  88292. * Enable or disable the sprites render time capture
  88293. */
  88294. set: function (value) {
  88295. var _this = this;
  88296. if (value === this._captureSpritesRenderTime) {
  88297. return;
  88298. }
  88299. this._captureSpritesRenderTime = value;
  88300. if (value) {
  88301. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88302. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88303. _this._spritesRenderTime.beginMonitoring();
  88304. });
  88305. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88306. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88307. _this._spritesRenderTime.endMonitoring(false);
  88308. });
  88309. }
  88310. else {
  88311. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88312. this._onBeforeSpritesRenderingObserver = null;
  88313. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88314. this._onAfterSpritesRenderingObserver = null;
  88315. }
  88316. },
  88317. enumerable: true,
  88318. configurable: true
  88319. });
  88320. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88321. /**
  88322. * Gets the perf counter used for physics time
  88323. */
  88324. get: function () {
  88325. return this._physicsTime;
  88326. },
  88327. enumerable: true,
  88328. configurable: true
  88329. });
  88330. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88331. /**
  88332. * Gets the physics time capture status
  88333. */
  88334. get: function () {
  88335. return this._capturePhysicsTime;
  88336. },
  88337. /**
  88338. * Enable or disable the physics time capture
  88339. */
  88340. set: function (value) {
  88341. var _this = this;
  88342. if (value === this._capturePhysicsTime) {
  88343. return;
  88344. }
  88345. this._capturePhysicsTime = value;
  88346. if (value) {
  88347. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88348. BABYLON.Tools.StartPerformanceCounter("Physics");
  88349. _this._physicsTime.beginMonitoring();
  88350. });
  88351. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88352. BABYLON.Tools.EndPerformanceCounter("Physics");
  88353. _this._physicsTime.endMonitoring();
  88354. });
  88355. }
  88356. else {
  88357. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88358. this._onBeforePhysicsObserver = null;
  88359. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88360. this._onAfterPhysicsObserver = null;
  88361. }
  88362. },
  88363. enumerable: true,
  88364. configurable: true
  88365. });
  88366. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88367. /**
  88368. * Gets the perf counter used for animations time
  88369. */
  88370. get: function () {
  88371. return this._animationsTime;
  88372. },
  88373. enumerable: true,
  88374. configurable: true
  88375. });
  88376. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88377. /**
  88378. * Gets the animations time capture status
  88379. */
  88380. get: function () {
  88381. return this._captureAnimationsTime;
  88382. },
  88383. /**
  88384. * Enable or disable the animations time capture
  88385. */
  88386. set: function (value) {
  88387. var _this = this;
  88388. if (value === this._captureAnimationsTime) {
  88389. return;
  88390. }
  88391. this._captureAnimationsTime = value;
  88392. if (value) {
  88393. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88394. _this._animationsTime.endMonitoring();
  88395. });
  88396. }
  88397. else {
  88398. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88399. this._onAfterAnimationsObserver = null;
  88400. }
  88401. },
  88402. enumerable: true,
  88403. configurable: true
  88404. });
  88405. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88406. /**
  88407. * Gets the perf counter used for frame time capture
  88408. */
  88409. get: function () {
  88410. return this._frameTime;
  88411. },
  88412. enumerable: true,
  88413. configurable: true
  88414. });
  88415. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88416. /**
  88417. * Gets the frame time capture status
  88418. */
  88419. get: function () {
  88420. return this._captureFrameTime;
  88421. },
  88422. /**
  88423. * Enable or disable the frame time capture
  88424. */
  88425. set: function (value) {
  88426. this._captureFrameTime = value;
  88427. },
  88428. enumerable: true,
  88429. configurable: true
  88430. });
  88431. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88432. /**
  88433. * Gets the perf counter used for inter-frames time capture
  88434. */
  88435. get: function () {
  88436. return this._interFrameTime;
  88437. },
  88438. enumerable: true,
  88439. configurable: true
  88440. });
  88441. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88442. /**
  88443. * Gets the inter-frames time capture status
  88444. */
  88445. get: function () {
  88446. return this._captureInterFrameTime;
  88447. },
  88448. /**
  88449. * Enable or disable the inter-frames time capture
  88450. */
  88451. set: function (value) {
  88452. this._captureInterFrameTime = value;
  88453. },
  88454. enumerable: true,
  88455. configurable: true
  88456. });
  88457. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88458. /**
  88459. * Gets the perf counter used for render time capture
  88460. */
  88461. get: function () {
  88462. return this._renderTime;
  88463. },
  88464. enumerable: true,
  88465. configurable: true
  88466. });
  88467. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88468. /**
  88469. * Gets the render time capture status
  88470. */
  88471. get: function () {
  88472. return this._captureRenderTime;
  88473. },
  88474. /**
  88475. * Enable or disable the render time capture
  88476. */
  88477. set: function (value) {
  88478. var _this = this;
  88479. if (value === this._captureRenderTime) {
  88480. return;
  88481. }
  88482. this._captureRenderTime = value;
  88483. if (value) {
  88484. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88485. _this._renderTime.beginMonitoring();
  88486. BABYLON.Tools.StartPerformanceCounter("Main render");
  88487. });
  88488. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88489. _this._renderTime.endMonitoring(false);
  88490. BABYLON.Tools.EndPerformanceCounter("Main render");
  88491. });
  88492. }
  88493. else {
  88494. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88495. this._onBeforeDrawPhaseObserver = null;
  88496. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88497. this._onAfterDrawPhaseObserver = null;
  88498. }
  88499. },
  88500. enumerable: true,
  88501. configurable: true
  88502. });
  88503. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88504. /**
  88505. * Gets the perf counter used for draw calls
  88506. */
  88507. get: function () {
  88508. return this.scene.getEngine()._drawCalls;
  88509. },
  88510. enumerable: true,
  88511. configurable: true
  88512. });
  88513. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88514. /**
  88515. * Gets the perf counter used for texture collisions
  88516. */
  88517. get: function () {
  88518. return this.scene.getEngine()._textureCollisions;
  88519. },
  88520. enumerable: true,
  88521. configurable: true
  88522. });
  88523. SceneInstrumentation.prototype.dispose = function () {
  88524. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88525. this._onAfterRenderObserver = null;
  88526. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88527. this._onBeforeActiveMeshesEvaluationObserver = null;
  88528. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88529. this._onAfterActiveMeshesEvaluationObserver = null;
  88530. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88531. this._onBeforeRenderTargetsRenderObserver = null;
  88532. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88533. this._onAfterRenderTargetsRenderObserver = null;
  88534. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88535. this._onBeforeAnimationsObserver = null;
  88536. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88537. this._onBeforeParticlesRenderingObserver = null;
  88538. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88539. this._onAfterParticlesRenderingObserver = null;
  88540. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88541. this._onBeforeSpritesRenderingObserver = null;
  88542. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88543. this._onAfterSpritesRenderingObserver = null;
  88544. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88545. this._onBeforeDrawPhaseObserver = null;
  88546. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88547. this._onAfterDrawPhaseObserver = null;
  88548. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88549. this._onBeforePhysicsObserver = null;
  88550. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88551. this._onAfterPhysicsObserver = null;
  88552. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88553. this._onAfterAnimationsObserver = null;
  88554. this.scene = null;
  88555. };
  88556. return SceneInstrumentation;
  88557. }());
  88558. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88559. })(BABYLON || (BABYLON = {}));
  88560. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88561. var BABYLON;
  88562. (function (BABYLON) {
  88563. var _TimeToken = /** @class */ (function () {
  88564. function _TimeToken() {
  88565. this._timeElapsedQueryEnded = false;
  88566. }
  88567. return _TimeToken;
  88568. }());
  88569. BABYLON._TimeToken = _TimeToken;
  88570. })(BABYLON || (BABYLON = {}));
  88571. //# sourceMappingURL=babylon.timeToken.js.map
  88572. var BABYLON;
  88573. (function (BABYLON) {
  88574. /**
  88575. * Background material defines definition.
  88576. * @ignore Mainly internal Use
  88577. */
  88578. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88579. __extends(BackgroundMaterialDefines, _super);
  88580. /**
  88581. * Constructor of the defines.
  88582. */
  88583. function BackgroundMaterialDefines() {
  88584. var _this = _super.call(this) || this;
  88585. /**
  88586. * True if the diffuse texture is in use.
  88587. */
  88588. _this.DIFFUSE = false;
  88589. /**
  88590. * The direct UV channel to use.
  88591. */
  88592. _this.DIFFUSEDIRECTUV = 0;
  88593. /**
  88594. * True if the diffuse texture is in gamma space.
  88595. */
  88596. _this.GAMMADIFFUSE = false;
  88597. /**
  88598. * True if the diffuse texture has opacity in the alpha channel.
  88599. */
  88600. _this.DIFFUSEHASALPHA = false;
  88601. /**
  88602. * True if you want the material to fade to transparent at grazing angle.
  88603. */
  88604. _this.OPACITYFRESNEL = false;
  88605. /**
  88606. * True if an extra blur needs to be added in the reflection.
  88607. */
  88608. _this.REFLECTIONBLUR = false;
  88609. /**
  88610. * True if you want the material to fade to reflection at grazing angle.
  88611. */
  88612. _this.REFLECTIONFRESNEL = false;
  88613. /**
  88614. * True if you want the material to falloff as far as you move away from the scene center.
  88615. */
  88616. _this.REFLECTIONFALLOFF = false;
  88617. /**
  88618. * False if the current Webgl implementation does not support the texture lod extension.
  88619. */
  88620. _this.TEXTURELODSUPPORT = false;
  88621. /**
  88622. * True to ensure the data are premultiplied.
  88623. */
  88624. _this.PREMULTIPLYALPHA = false;
  88625. /**
  88626. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88627. */
  88628. _this.USERGBCOLOR = false;
  88629. /**
  88630. * True to add noise in order to reduce the banding effect.
  88631. */
  88632. _this.NOISE = false;
  88633. /**
  88634. * is the reflection texture in BGR color scheme?
  88635. * Mainly used to solve a bug in ios10 video tag
  88636. */
  88637. _this.REFLECTIONBGR = false;
  88638. _this.IMAGEPROCESSING = false;
  88639. _this.VIGNETTE = false;
  88640. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88641. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88642. _this.TONEMAPPING = false;
  88643. _this.CONTRAST = false;
  88644. _this.COLORCURVES = false;
  88645. _this.COLORGRADING = false;
  88646. _this.COLORGRADING3D = false;
  88647. _this.SAMPLER3DGREENDEPTH = false;
  88648. _this.SAMPLER3DBGRMAP = false;
  88649. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88650. _this.EXPOSURE = false;
  88651. _this.GRAIN = false;
  88652. // Reflection.
  88653. _this.REFLECTION = false;
  88654. _this.REFLECTIONMAP_3D = false;
  88655. _this.REFLECTIONMAP_SPHERICAL = false;
  88656. _this.REFLECTIONMAP_PLANAR = false;
  88657. _this.REFLECTIONMAP_CUBIC = false;
  88658. _this.REFLECTIONMAP_PROJECTION = false;
  88659. _this.REFLECTIONMAP_SKYBOX = false;
  88660. _this.REFLECTIONMAP_EXPLICIT = false;
  88661. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88662. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88663. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88664. _this.INVERTCUBICMAP = false;
  88665. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88666. _this.LODINREFLECTIONALPHA = false;
  88667. _this.GAMMAREFLECTION = false;
  88668. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88669. // Default BJS.
  88670. _this.MAINUV1 = false;
  88671. _this.MAINUV2 = false;
  88672. _this.UV1 = false;
  88673. _this.UV2 = false;
  88674. _this.CLIPPLANE = false;
  88675. _this.POINTSIZE = false;
  88676. _this.FOG = false;
  88677. _this.NORMAL = false;
  88678. _this.NUM_BONE_INFLUENCERS = 0;
  88679. _this.BonesPerMesh = 0;
  88680. _this.INSTANCES = false;
  88681. _this.SHADOWFLOAT = false;
  88682. _this.rebuild();
  88683. return _this;
  88684. }
  88685. return BackgroundMaterialDefines;
  88686. }(BABYLON.MaterialDefines));
  88687. /**
  88688. * Background material used to create an efficient environement around your scene.
  88689. */
  88690. var BackgroundMaterial = /** @class */ (function (_super) {
  88691. __extends(BackgroundMaterial, _super);
  88692. /**
  88693. * Instantiates a Background Material in the given scene
  88694. * @param name The friendly name of the material
  88695. * @param scene The scene to add the material to
  88696. */
  88697. function BackgroundMaterial(name, scene) {
  88698. var _this = _super.call(this, name, scene) || this;
  88699. /**
  88700. * Key light Color (multiply against the R channel of the environement texture)
  88701. */
  88702. _this.primaryColor = BABYLON.Color3.White();
  88703. /**
  88704. * Key light Level (allowing HDR output of the background)
  88705. */
  88706. _this.primaryLevel = 1;
  88707. /**
  88708. * Secondary light Color (multiply against the G channel of the environement texture)
  88709. */
  88710. _this.secondaryColor = BABYLON.Color3.Gray();
  88711. /**
  88712. * Secondary light Level (allowing HDR output of the background)
  88713. */
  88714. _this.secondaryLevel = 1;
  88715. /**
  88716. * Tertiary light Color (multiply against the B channel of the environement texture)
  88717. */
  88718. _this.tertiaryColor = BABYLON.Color3.Black();
  88719. /**
  88720. * Tertiary light Level (allowing HDR output of the background)
  88721. */
  88722. _this.tertiaryLevel = 1;
  88723. /**
  88724. * Reflection Texture used in the material.
  88725. * Should be author in a specific way for the best result (refer to the documentation).
  88726. */
  88727. _this.reflectionTexture = null;
  88728. /**
  88729. * Reflection Texture level of blur.
  88730. *
  88731. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88732. * texture twice.
  88733. */
  88734. _this.reflectionBlur = 0;
  88735. /**
  88736. * Diffuse Texture used in the material.
  88737. * Should be author in a specific way for the best result (refer to the documentation).
  88738. */
  88739. _this.diffuseTexture = null;
  88740. _this._shadowLights = null;
  88741. /**
  88742. * Specify the list of lights casting shadow on the material.
  88743. * All scene shadow lights will be included if null.
  88744. */
  88745. _this.shadowLights = null;
  88746. /**
  88747. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88748. * soft lighting on the background.
  88749. */
  88750. _this.shadowBlurScale = 1;
  88751. /**
  88752. * Helps adjusting the shadow to a softer level if required.
  88753. * 0 means black shadows and 1 means no shadows.
  88754. */
  88755. _this.shadowLevel = 0;
  88756. /**
  88757. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88758. * It is usually zero but might be interesting to modify according to your setup.
  88759. */
  88760. _this.sceneCenter = BABYLON.Vector3.Zero();
  88761. /**
  88762. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88763. * This helps ensuring a nice transition when the camera goes under the ground.
  88764. */
  88765. _this.opacityFresnel = true;
  88766. /**
  88767. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88768. * This helps adding a mirror texture on the ground.
  88769. */
  88770. _this.reflectionFresnel = false;
  88771. /**
  88772. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88773. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88774. */
  88775. _this.reflectionFalloffDistance = 0.0;
  88776. /**
  88777. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88778. */
  88779. _this.reflectionAmount = 1.0;
  88780. /**
  88781. * This specifies the weight of the reflection at grazing angle.
  88782. */
  88783. _this.reflectionReflectance0 = 0.05;
  88784. /**
  88785. * This specifies the weight of the reflection at a perpendicular point of view.
  88786. */
  88787. _this.reflectionReflectance90 = 0.5;
  88788. /**
  88789. * Helps to directly use the maps channels instead of their level.
  88790. */
  88791. _this.useRGBColor = true;
  88792. /**
  88793. * This helps reducing the banding effect that could occur on the background.
  88794. */
  88795. _this.enableNoise = false;
  88796. _this._fovMultiplier = 1.0;
  88797. /**
  88798. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88799. * @type {boolean}
  88800. */
  88801. _this.useEquirectangularFOV = false;
  88802. _this._maxSimultaneousLights = 4;
  88803. /**
  88804. * Number of Simultaneous lights allowed on the material.
  88805. */
  88806. _this.maxSimultaneousLights = 4;
  88807. /**
  88808. * Keep track of the image processing observer to allow dispose and replace.
  88809. */
  88810. _this._imageProcessingObserver = null;
  88811. /**
  88812. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88813. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88814. */
  88815. _this.switchToBGR = false;
  88816. // Temp values kept as cache in the material.
  88817. _this._renderTargets = new BABYLON.SmartArray(16);
  88818. _this._reflectionControls = BABYLON.Vector4.Zero();
  88819. // Setup the default processing configuration to the scene.
  88820. _this._attachImageProcessingConfiguration(null);
  88821. _this.getRenderTargetTextures = function () {
  88822. _this._renderTargets.reset();
  88823. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88824. _this._renderTargets.push(_this._diffuseTexture);
  88825. }
  88826. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88827. _this._renderTargets.push(_this._reflectionTexture);
  88828. }
  88829. return _this._renderTargets;
  88830. };
  88831. return _this;
  88832. }
  88833. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88834. /**
  88835. * Sets the reflection reflectance fresnel values according to the default standard
  88836. * empirically know to work well :-)
  88837. */
  88838. set: function (value) {
  88839. var reflectionWeight = value;
  88840. if (reflectionWeight < 0.5) {
  88841. reflectionWeight = reflectionWeight * 2.0;
  88842. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88843. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88844. }
  88845. else {
  88846. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88847. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88848. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88849. }
  88850. },
  88851. enumerable: true,
  88852. configurable: true
  88853. });
  88854. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88855. /**
  88856. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88857. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88858. * Recommended to be keep at 1.0 except for special cases.
  88859. */
  88860. get: function () {
  88861. return this._fovMultiplier;
  88862. },
  88863. set: function (value) {
  88864. if (isNaN(value)) {
  88865. value = 1.0;
  88866. }
  88867. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88868. },
  88869. enumerable: true,
  88870. configurable: true
  88871. });
  88872. /**
  88873. * Attaches a new image processing configuration to the PBR Material.
  88874. * @param configuration (if null the scene configuration will be use)
  88875. */
  88876. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88877. var _this = this;
  88878. if (configuration === this._imageProcessingConfiguration) {
  88879. return;
  88880. }
  88881. // Detaches observer.
  88882. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88883. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88884. }
  88885. // Pick the scene configuration if needed.
  88886. if (!configuration) {
  88887. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88888. }
  88889. else {
  88890. this._imageProcessingConfiguration = configuration;
  88891. }
  88892. // Attaches observer.
  88893. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88894. _this._markAllSubMeshesAsImageProcessingDirty();
  88895. });
  88896. };
  88897. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88898. /**
  88899. * Gets the image processing configuration used either in this material.
  88900. */
  88901. get: function () {
  88902. return this._imageProcessingConfiguration;
  88903. },
  88904. /**
  88905. * Sets the Default image processing configuration used either in the this material.
  88906. *
  88907. * If sets to null, the scene one is in use.
  88908. */
  88909. set: function (value) {
  88910. this._attachImageProcessingConfiguration(value);
  88911. // Ensure the effect will be rebuilt.
  88912. this._markAllSubMeshesAsTexturesDirty();
  88913. },
  88914. enumerable: true,
  88915. configurable: true
  88916. });
  88917. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88918. /**
  88919. * Gets wether the color curves effect is enabled.
  88920. */
  88921. get: function () {
  88922. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88923. },
  88924. /**
  88925. * Sets wether the color curves effect is enabled.
  88926. */
  88927. set: function (value) {
  88928. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88929. },
  88930. enumerable: true,
  88931. configurable: true
  88932. });
  88933. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88934. /**
  88935. * Gets wether the color grading effect is enabled.
  88936. */
  88937. get: function () {
  88938. return this.imageProcessingConfiguration.colorGradingEnabled;
  88939. },
  88940. /**
  88941. * Gets wether the color grading effect is enabled.
  88942. */
  88943. set: function (value) {
  88944. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88945. },
  88946. enumerable: true,
  88947. configurable: true
  88948. });
  88949. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88950. /**
  88951. * Gets wether tonemapping is enabled or not.
  88952. */
  88953. get: function () {
  88954. return this._imageProcessingConfiguration.toneMappingEnabled;
  88955. },
  88956. /**
  88957. * Sets wether tonemapping is enabled or not
  88958. */
  88959. set: function (value) {
  88960. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88961. },
  88962. enumerable: true,
  88963. configurable: true
  88964. });
  88965. ;
  88966. ;
  88967. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88968. /**
  88969. * The camera exposure used on this material.
  88970. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88971. * This corresponds to a photographic exposure.
  88972. */
  88973. get: function () {
  88974. return this._imageProcessingConfiguration.exposure;
  88975. },
  88976. /**
  88977. * The camera exposure used on this material.
  88978. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88979. * This corresponds to a photographic exposure.
  88980. */
  88981. set: function (value) {
  88982. this._imageProcessingConfiguration.exposure = value;
  88983. },
  88984. enumerable: true,
  88985. configurable: true
  88986. });
  88987. ;
  88988. ;
  88989. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88990. /**
  88991. * Gets The camera contrast used on this material.
  88992. */
  88993. get: function () {
  88994. return this._imageProcessingConfiguration.contrast;
  88995. },
  88996. /**
  88997. * Sets The camera contrast used on this material.
  88998. */
  88999. set: function (value) {
  89000. this._imageProcessingConfiguration.contrast = value;
  89001. },
  89002. enumerable: true,
  89003. configurable: true
  89004. });
  89005. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89006. /**
  89007. * Gets the Color Grading 2D Lookup Texture.
  89008. */
  89009. get: function () {
  89010. return this._imageProcessingConfiguration.colorGradingTexture;
  89011. },
  89012. /**
  89013. * Sets the Color Grading 2D Lookup Texture.
  89014. */
  89015. set: function (value) {
  89016. this.imageProcessingConfiguration.colorGradingTexture = value;
  89017. },
  89018. enumerable: true,
  89019. configurable: true
  89020. });
  89021. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89022. /**
  89023. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89024. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89025. * 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;
  89026. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89027. */
  89028. get: function () {
  89029. return this.imageProcessingConfiguration.colorCurves;
  89030. },
  89031. /**
  89032. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89033. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89034. * 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;
  89035. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89036. */
  89037. set: function (value) {
  89038. this.imageProcessingConfiguration.colorCurves = value;
  89039. },
  89040. enumerable: true,
  89041. configurable: true
  89042. });
  89043. /**
  89044. * The entire material has been created in order to prevent overdraw.
  89045. * @returns false
  89046. */
  89047. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89048. return true;
  89049. };
  89050. /**
  89051. * The entire material has been created in order to prevent overdraw.
  89052. * @returns true if blending is enable
  89053. */
  89054. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89055. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89056. };
  89057. /**
  89058. * Checks wether the material is ready to be rendered for a given mesh.
  89059. * @param mesh The mesh to render
  89060. * @param subMesh The submesh to check against
  89061. * @param useInstances Specify wether or not the material is used with instances
  89062. * @returns true if all the dependencies are ready (Textures, Effects...)
  89063. */
  89064. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89065. var _this = this;
  89066. if (useInstances === void 0) { useInstances = false; }
  89067. if (subMesh.effect && this.isFrozen) {
  89068. if (this._wasPreviouslyReady) {
  89069. return true;
  89070. }
  89071. }
  89072. if (!subMesh._materialDefines) {
  89073. subMesh._materialDefines = new BackgroundMaterialDefines();
  89074. }
  89075. var scene = this.getScene();
  89076. var defines = subMesh._materialDefines;
  89077. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89078. if (defines._renderId === scene.getRenderId()) {
  89079. return true;
  89080. }
  89081. }
  89082. var engine = scene.getEngine();
  89083. // Lights
  89084. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89085. defines._needNormals = true;
  89086. // Textures
  89087. if (defines._areTexturesDirty) {
  89088. defines._needUVs = false;
  89089. if (scene.texturesEnabled) {
  89090. if (scene.getEngine().getCaps().textureLOD) {
  89091. defines.TEXTURELODSUPPORT = true;
  89092. }
  89093. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89094. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89095. return false;
  89096. }
  89097. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89098. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89099. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89100. defines.OPACITYFRESNEL = this._opacityFresnel;
  89101. }
  89102. else {
  89103. defines.DIFFUSE = false;
  89104. defines.DIFFUSEHASALPHA = false;
  89105. defines.GAMMADIFFUSE = false;
  89106. defines.OPACITYFRESNEL = false;
  89107. }
  89108. var reflectionTexture = this._reflectionTexture;
  89109. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89110. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89111. return false;
  89112. }
  89113. defines.REFLECTION = true;
  89114. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89115. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89116. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89117. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89118. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89119. defines.REFLECTIONBGR = this.switchToBGR;
  89120. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89121. defines.INVERTCUBICMAP = true;
  89122. }
  89123. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89124. switch (reflectionTexture.coordinatesMode) {
  89125. case BABYLON.Texture.CUBIC_MODE:
  89126. case BABYLON.Texture.INVCUBIC_MODE:
  89127. defines.REFLECTIONMAP_CUBIC = true;
  89128. break;
  89129. case BABYLON.Texture.EXPLICIT_MODE:
  89130. defines.REFLECTIONMAP_EXPLICIT = true;
  89131. break;
  89132. case BABYLON.Texture.PLANAR_MODE:
  89133. defines.REFLECTIONMAP_PLANAR = true;
  89134. break;
  89135. case BABYLON.Texture.PROJECTION_MODE:
  89136. defines.REFLECTIONMAP_PROJECTION = true;
  89137. break;
  89138. case BABYLON.Texture.SKYBOX_MODE:
  89139. defines.REFLECTIONMAP_SKYBOX = true;
  89140. break;
  89141. case BABYLON.Texture.SPHERICAL_MODE:
  89142. defines.REFLECTIONMAP_SPHERICAL = true;
  89143. break;
  89144. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89145. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89146. break;
  89147. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89148. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89149. break;
  89150. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89151. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89152. break;
  89153. }
  89154. if (this.reflectionFresnel) {
  89155. defines.REFLECTIONFRESNEL = true;
  89156. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89157. this._reflectionControls.x = this.reflectionAmount;
  89158. this._reflectionControls.y = this.reflectionReflectance0;
  89159. this._reflectionControls.z = this.reflectionReflectance90;
  89160. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89161. }
  89162. else {
  89163. defines.REFLECTIONFRESNEL = false;
  89164. defines.REFLECTIONFALLOFF = false;
  89165. }
  89166. }
  89167. else {
  89168. defines.REFLECTION = false;
  89169. defines.REFLECTIONFALLOFF = false;
  89170. defines.REFLECTIONBLUR = false;
  89171. defines.REFLECTIONMAP_3D = false;
  89172. defines.REFLECTIONMAP_SPHERICAL = false;
  89173. defines.REFLECTIONMAP_PLANAR = false;
  89174. defines.REFLECTIONMAP_CUBIC = false;
  89175. defines.REFLECTIONMAP_PROJECTION = false;
  89176. defines.REFLECTIONMAP_SKYBOX = false;
  89177. defines.REFLECTIONMAP_EXPLICIT = false;
  89178. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89179. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89180. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89181. defines.INVERTCUBICMAP = false;
  89182. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89183. defines.LODINREFLECTIONALPHA = false;
  89184. defines.GAMMAREFLECTION = false;
  89185. }
  89186. }
  89187. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89188. defines.USERGBCOLOR = this._useRGBColor;
  89189. defines.NOISE = this._enableNoise;
  89190. }
  89191. if (defines._areImageProcessingDirty) {
  89192. if (!this._imageProcessingConfiguration.isReady()) {
  89193. return false;
  89194. }
  89195. this._imageProcessingConfiguration.prepareDefines(defines);
  89196. }
  89197. // Misc.
  89198. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89199. // Values that need to be evaluated on every frame
  89200. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89201. // Attribs
  89202. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89203. if (mesh) {
  89204. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89205. mesh.createNormals(true);
  89206. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89207. }
  89208. }
  89209. }
  89210. // Get correct effect
  89211. if (defines.isDirty) {
  89212. defines.markAsProcessed();
  89213. scene.resetCachedMaterial();
  89214. // Fallbacks
  89215. var fallbacks = new BABYLON.EffectFallbacks();
  89216. if (defines.FOG) {
  89217. fallbacks.addFallback(0, "FOG");
  89218. }
  89219. if (defines.POINTSIZE) {
  89220. fallbacks.addFallback(1, "POINTSIZE");
  89221. }
  89222. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  89223. if (defines.NUM_BONE_INFLUENCERS > 0) {
  89224. fallbacks.addCPUSkinningFallback(0, mesh);
  89225. }
  89226. //Attributes
  89227. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89228. if (defines.NORMAL) {
  89229. attribs.push(BABYLON.VertexBuffer.NormalKind);
  89230. }
  89231. if (defines.UV1) {
  89232. attribs.push(BABYLON.VertexBuffer.UVKind);
  89233. }
  89234. if (defines.UV2) {
  89235. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89236. }
  89237. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  89238. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  89239. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  89240. "vFogInfos", "vFogColor", "pointSize",
  89241. "vClipPlane", "mBones",
  89242. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  89243. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89244. "shadowLevel", "alpha",
  89245. "vBackgroundCenter", "vReflectionControl",
  89246. "vDiffuseInfos", "diffuseMatrix",
  89247. ];
  89248. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89249. var uniformBuffers = ["Material", "Scene"];
  89250. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89251. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89252. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89253. uniformsNames: uniforms,
  89254. uniformBuffersNames: uniformBuffers,
  89255. samplers: samplers,
  89256. defines: defines,
  89257. maxSimultaneousLights: this._maxSimultaneousLights
  89258. });
  89259. var onCompiled = function (effect) {
  89260. if (_this.onCompiled) {
  89261. _this.onCompiled(effect);
  89262. }
  89263. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89264. };
  89265. var join = defines.toString();
  89266. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89267. attributes: attribs,
  89268. uniformsNames: uniforms,
  89269. uniformBuffersNames: uniformBuffers,
  89270. samplers: samplers,
  89271. defines: join,
  89272. fallbacks: fallbacks,
  89273. onCompiled: onCompiled,
  89274. onError: this.onError,
  89275. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89276. }, engine), defines);
  89277. this.buildUniformLayout();
  89278. }
  89279. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89280. return false;
  89281. }
  89282. defines._renderId = scene.getRenderId();
  89283. this._wasPreviouslyReady = true;
  89284. return true;
  89285. };
  89286. /**
  89287. * Build the uniform buffer used in the material.
  89288. */
  89289. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89290. // Order is important !
  89291. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89292. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89293. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89294. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89295. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89296. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89297. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89298. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89299. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89300. this._uniformBuffer.addUniform("pointSize", 1);
  89301. this._uniformBuffer.addUniform("shadowLevel", 1);
  89302. this._uniformBuffer.addUniform("alpha", 1);
  89303. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89304. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89305. this._uniformBuffer.create();
  89306. };
  89307. /**
  89308. * Unbind the material.
  89309. */
  89310. BackgroundMaterial.prototype.unbind = function () {
  89311. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89312. this._uniformBuffer.setTexture("diffuseSampler", null);
  89313. }
  89314. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89315. this._uniformBuffer.setTexture("reflectionSampler", null);
  89316. }
  89317. _super.prototype.unbind.call(this);
  89318. };
  89319. /**
  89320. * Bind only the world matrix to the material.
  89321. * @param world The world matrix to bind.
  89322. */
  89323. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89324. this._activeEffect.setMatrix("world", world);
  89325. };
  89326. /**
  89327. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89328. * @param world The world matrix to bind.
  89329. * @param subMesh The submesh to bind for.
  89330. */
  89331. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89332. var scene = this.getScene();
  89333. var defines = subMesh._materialDefines;
  89334. if (!defines) {
  89335. return;
  89336. }
  89337. var effect = subMesh.effect;
  89338. if (!effect) {
  89339. return;
  89340. }
  89341. this._activeEffect = effect;
  89342. // Matrices
  89343. this.bindOnlyWorldMatrix(world);
  89344. // Bones
  89345. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89346. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89347. if (mustRebind) {
  89348. this._uniformBuffer.bindToEffect(effect, "Material");
  89349. this.bindViewProjection(effect);
  89350. var reflectionTexture = this._reflectionTexture;
  89351. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89352. // Texture uniforms
  89353. if (scene.texturesEnabled) {
  89354. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89355. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89356. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89357. }
  89358. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89359. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89360. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89361. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89362. }
  89363. }
  89364. if (this.shadowLevel > 0) {
  89365. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89366. }
  89367. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89368. // Point size
  89369. if (this.pointsCloud) {
  89370. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89371. }
  89372. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89373. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89374. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89375. }
  89376. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89377. // Textures
  89378. if (scene.texturesEnabled) {
  89379. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89380. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89381. }
  89382. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89383. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89384. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89385. }
  89386. else if (!defines.REFLECTIONBLUR) {
  89387. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89388. }
  89389. else {
  89390. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89391. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89392. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89393. }
  89394. if (defines.REFLECTIONFRESNEL) {
  89395. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89396. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89397. }
  89398. }
  89399. }
  89400. // Clip plane
  89401. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89402. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89403. }
  89404. if (mustRebind || !this.isFrozen) {
  89405. if (scene.lightsEnabled) {
  89406. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89407. }
  89408. // View
  89409. this.bindView(effect);
  89410. // Fog
  89411. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89412. // image processing
  89413. this._imageProcessingConfiguration.bind(this._activeEffect);
  89414. }
  89415. this._uniformBuffer.update();
  89416. this._afterBind(mesh);
  89417. };
  89418. /**
  89419. * Dispose the material.
  89420. * @param forceDisposeEffect Force disposal of the associated effect.
  89421. * @param forceDisposeTextures Force disposal of the associated textures.
  89422. */
  89423. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89424. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89425. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89426. if (forceDisposeTextures) {
  89427. if (this.diffuseTexture) {
  89428. this.diffuseTexture.dispose();
  89429. }
  89430. if (this.reflectionTexture) {
  89431. this.reflectionTexture.dispose();
  89432. }
  89433. }
  89434. this._renderTargets.dispose();
  89435. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89436. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89437. }
  89438. _super.prototype.dispose.call(this, forceDisposeEffect);
  89439. };
  89440. /**
  89441. * Clones the material.
  89442. * @param name The cloned name.
  89443. * @returns The cloned material.
  89444. */
  89445. BackgroundMaterial.prototype.clone = function (name) {
  89446. var _this = this;
  89447. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89448. };
  89449. /**
  89450. * Serializes the current material to its JSON representation.
  89451. * @returns The JSON representation.
  89452. */
  89453. BackgroundMaterial.prototype.serialize = function () {
  89454. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89455. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89456. return serializationObject;
  89457. };
  89458. /**
  89459. * Gets the class name of the material
  89460. * @returns "BackgroundMaterial"
  89461. */
  89462. BackgroundMaterial.prototype.getClassName = function () {
  89463. return "BackgroundMaterial";
  89464. };
  89465. /**
  89466. * Parse a JSON input to create back a background material.
  89467. * @param source The JSON data to parse
  89468. * @param scene The scene to create the parsed material in
  89469. * @param rootUrl The root url of the assets the material depends upon
  89470. * @returns the instantiated BackgroundMaterial.
  89471. */
  89472. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89473. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89474. };
  89475. /**
  89476. * Standard reflectance value at parallel view angle.
  89477. */
  89478. BackgroundMaterial.StandardReflectance0 = 0.05;
  89479. /**
  89480. * Standard reflectance value at grazing angle.
  89481. */
  89482. BackgroundMaterial.StandardReflectance90 = 0.5;
  89483. __decorate([
  89484. BABYLON.serializeAsColor3()
  89485. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89486. __decorate([
  89487. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89488. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89489. __decorate([
  89490. BABYLON.serialize()
  89491. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89492. __decorate([
  89493. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89494. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89495. __decorate([
  89496. BABYLON.serializeAsColor3()
  89497. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89498. __decorate([
  89499. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89500. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89501. __decorate([
  89502. BABYLON.serialize()
  89503. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89504. __decorate([
  89505. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89506. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89507. __decorate([
  89508. BABYLON.serializeAsColor3()
  89509. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89510. __decorate([
  89511. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89512. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89513. __decorate([
  89514. BABYLON.serialize()
  89515. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89516. __decorate([
  89517. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89518. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89519. __decorate([
  89520. BABYLON.serializeAsTexture()
  89521. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89522. __decorate([
  89523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89524. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89525. __decorate([
  89526. BABYLON.serialize()
  89527. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89528. __decorate([
  89529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89530. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89531. __decorate([
  89532. BABYLON.serializeAsTexture()
  89533. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89534. __decorate([
  89535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89536. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89537. __decorate([
  89538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89539. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89540. __decorate([
  89541. BABYLON.serialize()
  89542. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89543. __decorate([
  89544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89545. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89546. __decorate([
  89547. BABYLON.serialize()
  89548. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89549. __decorate([
  89550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89551. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89552. __decorate([
  89553. BABYLON.serializeAsVector3()
  89554. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89555. __decorate([
  89556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89557. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89558. __decorate([
  89559. BABYLON.serialize()
  89560. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89561. __decorate([
  89562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89563. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89564. __decorate([
  89565. BABYLON.serialize()
  89566. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89567. __decorate([
  89568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89569. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89570. __decorate([
  89571. BABYLON.serialize()
  89572. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89573. __decorate([
  89574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89575. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89576. __decorate([
  89577. BABYLON.serialize()
  89578. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89579. __decorate([
  89580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89581. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89582. __decorate([
  89583. BABYLON.serialize()
  89584. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89585. __decorate([
  89586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89587. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89588. __decorate([
  89589. BABYLON.serialize()
  89590. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89591. __decorate([
  89592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89593. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89594. __decorate([
  89595. BABYLON.serialize()
  89596. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89597. __decorate([
  89598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89599. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89600. __decorate([
  89601. BABYLON.serialize()
  89602. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89603. __decorate([
  89604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89605. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89606. __decorate([
  89607. BABYLON.serialize()
  89608. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89609. __decorate([
  89610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89611. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89612. __decorate([
  89613. BABYLON.serializeAsImageProcessingConfiguration()
  89614. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89615. return BackgroundMaterial;
  89616. }(BABYLON.PushMaterial));
  89617. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89618. })(BABYLON || (BABYLON = {}));
  89619. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89620. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89621. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89622. s = arguments[i];
  89623. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89624. t[p] = s[p];
  89625. }
  89626. return t;
  89627. };
  89628. var BABYLON;
  89629. (function (BABYLON) {
  89630. /**
  89631. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89632. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89633. * It also helps with the default setup of your imageProcessing configuration.
  89634. */
  89635. var EnvironmentHelper = /** @class */ (function () {
  89636. /**
  89637. * constructor
  89638. * @param options
  89639. * @param scene The scene to add the material to
  89640. */
  89641. function EnvironmentHelper(options, scene) {
  89642. var _this = this;
  89643. this._errorHandler = function (message, exception) {
  89644. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  89645. };
  89646. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89647. this._scene = scene;
  89648. this.onErrorObservable = new BABYLON.Observable();
  89649. this._setupBackground();
  89650. this._setupImageProcessing();
  89651. }
  89652. /**
  89653. * Creates the default options for the helper.
  89654. */
  89655. EnvironmentHelper._getDefaultOptions = function () {
  89656. return {
  89657. createGround: true,
  89658. groundSize: 15,
  89659. groundTexture: this._groundTextureCDNUrl,
  89660. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89661. groundOpacity: 0.9,
  89662. enableGroundShadow: true,
  89663. groundShadowLevel: 0.5,
  89664. enableGroundMirror: false,
  89665. groundMirrorSizeRatio: 0.3,
  89666. groundMirrorBlurKernel: 64,
  89667. groundMirrorAmount: 1,
  89668. groundMirrorFresnelWeight: 1,
  89669. groundMirrorFallOffDistance: 0,
  89670. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89671. groundYBias: 0.00001,
  89672. createSkybox: true,
  89673. skyboxSize: 20,
  89674. skyboxTexture: this._skyboxTextureCDNUrl,
  89675. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89676. backgroundYRotation: 0,
  89677. sizeAuto: true,
  89678. rootPosition: BABYLON.Vector3.Zero(),
  89679. setupImageProcessing: true,
  89680. environmentTexture: this._environmentTextureCDNUrl,
  89681. cameraExposure: 0.8,
  89682. cameraContrast: 1.2,
  89683. toneMappingEnabled: true,
  89684. };
  89685. };
  89686. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89687. /**
  89688. * Gets the root mesh created by the helper.
  89689. */
  89690. get: function () {
  89691. return this._rootMesh;
  89692. },
  89693. enumerable: true,
  89694. configurable: true
  89695. });
  89696. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89697. /**
  89698. * Gets the skybox created by the helper.
  89699. */
  89700. get: function () {
  89701. return this._skybox;
  89702. },
  89703. enumerable: true,
  89704. configurable: true
  89705. });
  89706. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89707. /**
  89708. * Gets the skybox texture created by the helper.
  89709. */
  89710. get: function () {
  89711. return this._skyboxTexture;
  89712. },
  89713. enumerable: true,
  89714. configurable: true
  89715. });
  89716. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89717. /**
  89718. * Gets the skybox material created by the helper.
  89719. */
  89720. get: function () {
  89721. return this._skyboxMaterial;
  89722. },
  89723. enumerable: true,
  89724. configurable: true
  89725. });
  89726. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89727. /**
  89728. * Gets the ground mesh created by the helper.
  89729. */
  89730. get: function () {
  89731. return this._ground;
  89732. },
  89733. enumerable: true,
  89734. configurable: true
  89735. });
  89736. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89737. /**
  89738. * Gets the ground texture created by the helper.
  89739. */
  89740. get: function () {
  89741. return this._groundTexture;
  89742. },
  89743. enumerable: true,
  89744. configurable: true
  89745. });
  89746. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89747. /**
  89748. * Gets the ground mirror created by the helper.
  89749. */
  89750. get: function () {
  89751. return this._groundMirror;
  89752. },
  89753. enumerable: true,
  89754. configurable: true
  89755. });
  89756. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89757. /**
  89758. * Gets the ground mirror render list to helps pushing the meshes
  89759. * you wish in the ground reflection.
  89760. */
  89761. get: function () {
  89762. if (this._groundMirror) {
  89763. return this._groundMirror.renderList;
  89764. }
  89765. return null;
  89766. },
  89767. enumerable: true,
  89768. configurable: true
  89769. });
  89770. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89771. /**
  89772. * Gets the ground material created by the helper.
  89773. */
  89774. get: function () {
  89775. return this._groundMaterial;
  89776. },
  89777. enumerable: true,
  89778. configurable: true
  89779. });
  89780. /**
  89781. * Updates the background according to the new options
  89782. * @param options
  89783. */
  89784. EnvironmentHelper.prototype.updateOptions = function (options) {
  89785. var newOptions = __assign({}, this._options, options);
  89786. if (this._ground && !newOptions.createGround) {
  89787. this._ground.dispose();
  89788. this._ground = null;
  89789. }
  89790. if (this._groundMaterial && !newOptions.createGround) {
  89791. this._groundMaterial.dispose();
  89792. this._groundMaterial = null;
  89793. }
  89794. if (this._groundTexture) {
  89795. if (this._options.groundTexture != newOptions.groundTexture) {
  89796. this._groundTexture.dispose();
  89797. this._groundTexture = null;
  89798. }
  89799. }
  89800. if (this._skybox && !newOptions.createSkybox) {
  89801. this._skybox.dispose();
  89802. this._skybox = null;
  89803. }
  89804. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89805. this._skyboxMaterial.dispose();
  89806. this._skyboxMaterial = null;
  89807. }
  89808. if (this._skyboxTexture) {
  89809. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89810. this._skyboxTexture.dispose();
  89811. this._skyboxTexture = null;
  89812. }
  89813. }
  89814. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89815. this._groundMirror.dispose();
  89816. this._groundMirror = null;
  89817. }
  89818. if (this._scene.environmentTexture) {
  89819. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89820. this._scene.environmentTexture.dispose();
  89821. }
  89822. }
  89823. this._options = newOptions;
  89824. this._setupBackground();
  89825. this._setupImageProcessing();
  89826. };
  89827. /**
  89828. * Sets the primary color of all the available elements.
  89829. * @param color
  89830. */
  89831. EnvironmentHelper.prototype.setMainColor = function (color) {
  89832. if (this.groundMaterial) {
  89833. this.groundMaterial.primaryColor = color;
  89834. }
  89835. if (this.skyboxMaterial) {
  89836. this.skyboxMaterial.primaryColor = color;
  89837. }
  89838. if (this.groundMirror) {
  89839. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89840. }
  89841. };
  89842. /**
  89843. * Setup the image processing according to the specified options.
  89844. */
  89845. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89846. if (this._options.setupImageProcessing) {
  89847. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89848. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89849. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89850. this._setupEnvironmentTexture();
  89851. }
  89852. };
  89853. /**
  89854. * Setup the environment texture according to the specified options.
  89855. */
  89856. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89857. if (this._scene.environmentTexture) {
  89858. return;
  89859. }
  89860. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89861. this._scene.environmentTexture = this._options.environmentTexture;
  89862. return;
  89863. }
  89864. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89865. this._scene.environmentTexture = environmentTexture;
  89866. };
  89867. /**
  89868. * Setup the background according to the specified options.
  89869. */
  89870. EnvironmentHelper.prototype._setupBackground = function () {
  89871. if (!this._rootMesh) {
  89872. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89873. }
  89874. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89875. var sceneSize = this._getSceneSize();
  89876. if (this._options.createGround) {
  89877. this._setupGround(sceneSize);
  89878. this._setupGroundMaterial();
  89879. this._setupGroundDiffuseTexture();
  89880. if (this._options.enableGroundMirror) {
  89881. this._setupGroundMirrorTexture(sceneSize);
  89882. }
  89883. this._setupMirrorInGroundMaterial();
  89884. }
  89885. if (this._options.createSkybox) {
  89886. this._setupSkybox(sceneSize);
  89887. this._setupSkyboxMaterial();
  89888. this._setupSkyboxReflectionTexture();
  89889. }
  89890. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89891. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89892. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89893. };
  89894. /**
  89895. * Get the scene sizes according to the setup.
  89896. */
  89897. EnvironmentHelper.prototype._getSceneSize = function () {
  89898. var _this = this;
  89899. var groundSize = this._options.groundSize;
  89900. var skyboxSize = this._options.skyboxSize;
  89901. var rootPosition = this._options.rootPosition;
  89902. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89903. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89904. }
  89905. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89906. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89907. });
  89908. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89909. if (this._options.sizeAuto) {
  89910. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89911. this._scene.activeCamera.upperRadiusLimit) {
  89912. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89913. skyboxSize = groundSize;
  89914. }
  89915. var sceneDiagonalLenght = sceneDiagonal.length();
  89916. if (sceneDiagonalLenght > groundSize) {
  89917. groundSize = sceneDiagonalLenght * 2;
  89918. skyboxSize = groundSize;
  89919. }
  89920. // 10 % bigger.
  89921. groundSize *= 1.1;
  89922. skyboxSize *= 1.5;
  89923. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89924. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89925. }
  89926. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89927. };
  89928. /**
  89929. * Setup the ground according to the specified options.
  89930. */
  89931. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89932. var _this = this;
  89933. if (!this._ground) {
  89934. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89935. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89936. this._ground.parent = this._rootMesh;
  89937. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89938. }
  89939. this._ground.receiveShadows = this._options.enableGroundShadow;
  89940. };
  89941. /**
  89942. * Setup the ground material according to the specified options.
  89943. */
  89944. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89945. if (!this._groundMaterial) {
  89946. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89947. }
  89948. this._groundMaterial.alpha = this._options.groundOpacity;
  89949. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89950. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89951. this._groundMaterial.primaryLevel = 1;
  89952. this._groundMaterial.primaryColor = this._options.groundColor;
  89953. this._groundMaterial.secondaryLevel = 0;
  89954. this._groundMaterial.tertiaryLevel = 0;
  89955. this._groundMaterial.useRGBColor = false;
  89956. this._groundMaterial.enableNoise = true;
  89957. if (this._ground) {
  89958. this._ground.material = this._groundMaterial;
  89959. }
  89960. };
  89961. /**
  89962. * Setup the ground diffuse texture according to the specified options.
  89963. */
  89964. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89965. if (!this._groundMaterial) {
  89966. return;
  89967. }
  89968. if (this._groundTexture) {
  89969. return;
  89970. }
  89971. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89972. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89973. return;
  89974. }
  89975. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89976. diffuseTexture.gammaSpace = false;
  89977. diffuseTexture.hasAlpha = true;
  89978. this._groundMaterial.diffuseTexture = diffuseTexture;
  89979. };
  89980. /**
  89981. * Setup the ground mirror texture according to the specified options.
  89982. */
  89983. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89984. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89985. if (!this._groundMirror) {
  89986. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89987. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89988. this._groundMirror.anisotropicFilteringLevel = 1;
  89989. this._groundMirror.wrapU = wrapping;
  89990. this._groundMirror.wrapV = wrapping;
  89991. this._groundMirror.gammaSpace = false;
  89992. if (this._groundMirror.renderList) {
  89993. for (var i = 0; i < this._scene.meshes.length; i++) {
  89994. var mesh = this._scene.meshes[i];
  89995. if (mesh !== this._ground &&
  89996. mesh !== this._skybox &&
  89997. mesh !== this._rootMesh) {
  89998. this._groundMirror.renderList.push(mesh);
  89999. }
  90000. }
  90001. }
  90002. }
  90003. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90004. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90005. };
  90006. /**
  90007. * Setup the ground to receive the mirror texture.
  90008. */
  90009. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90010. if (this._groundMaterial) {
  90011. this._groundMaterial.reflectionTexture = this._groundMirror;
  90012. this._groundMaterial.reflectionFresnel = true;
  90013. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90014. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90015. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90016. }
  90017. };
  90018. /**
  90019. * Setup the skybox according to the specified options.
  90020. */
  90021. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90022. var _this = this;
  90023. if (!this._skybox) {
  90024. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90025. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90026. }
  90027. this._skybox.parent = this._rootMesh;
  90028. };
  90029. /**
  90030. * Setup the skybox material according to the specified options.
  90031. */
  90032. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90033. if (!this._skybox) {
  90034. return;
  90035. }
  90036. if (!this._skyboxMaterial) {
  90037. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90038. }
  90039. this._skyboxMaterial.useRGBColor = false;
  90040. this._skyboxMaterial.primaryLevel = 1;
  90041. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90042. this._skyboxMaterial.secondaryLevel = 0;
  90043. this._skyboxMaterial.tertiaryLevel = 0;
  90044. this._skyboxMaterial.enableNoise = true;
  90045. this._skybox.material = this._skyboxMaterial;
  90046. };
  90047. /**
  90048. * Setup the skybox reflection texture according to the specified options.
  90049. */
  90050. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90051. if (!this._skyboxMaterial) {
  90052. return;
  90053. }
  90054. if (this._skyboxTexture) {
  90055. return;
  90056. }
  90057. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90058. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90059. return;
  90060. }
  90061. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90062. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90063. this._skyboxTexture.gammaSpace = false;
  90064. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90065. };
  90066. /**
  90067. * Dispose all the elements created by the Helper.
  90068. */
  90069. EnvironmentHelper.prototype.dispose = function () {
  90070. if (this._groundMaterial) {
  90071. this._groundMaterial.dispose(true, true);
  90072. }
  90073. if (this._skyboxMaterial) {
  90074. this._skyboxMaterial.dispose(true, true);
  90075. }
  90076. this._rootMesh.dispose(false);
  90077. };
  90078. /**
  90079. * Default ground texture URL.
  90080. */
  90081. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90082. /**
  90083. * Default skybox texture URL.
  90084. */
  90085. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90086. /**
  90087. * Default environment texture URL.
  90088. */
  90089. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90090. return EnvironmentHelper;
  90091. }());
  90092. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90093. })(BABYLON || (BABYLON = {}));
  90094. //# sourceMappingURL=babylon.environmentHelper.js.map
  90095. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  90096. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  90097. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90098. var BABYLON;
  90099. (function (BABYLON) {
  90100. var GridMaterialDefines = /** @class */ (function (_super) {
  90101. __extends(GridMaterialDefines, _super);
  90102. function GridMaterialDefines() {
  90103. var _this = _super.call(this) || this;
  90104. _this.TRANSPARENT = false;
  90105. _this.FOG = false;
  90106. _this.PREMULTIPLYALPHA = false;
  90107. _this.rebuild();
  90108. return _this;
  90109. }
  90110. return GridMaterialDefines;
  90111. }(BABYLON.MaterialDefines));
  90112. /**
  90113. * The grid materials allows you to wrap any shape with a grid.
  90114. * Colors are customizable.
  90115. */
  90116. var GridMaterial = /** @class */ (function (_super) {
  90117. __extends(GridMaterial, _super);
  90118. /**
  90119. * constructor
  90120. * @param name The name given to the material in order to identify it afterwards.
  90121. * @param scene The scene the material is used in.
  90122. */
  90123. function GridMaterial(name, scene) {
  90124. var _this = _super.call(this, name, scene) || this;
  90125. /**
  90126. * Main color of the grid (e.g. between lines)
  90127. */
  90128. _this.mainColor = BABYLON.Color3.Black();
  90129. /**
  90130. * Color of the grid lines.
  90131. */
  90132. _this.lineColor = BABYLON.Color3.Teal();
  90133. /**
  90134. * The scale of the grid compared to unit.
  90135. */
  90136. _this.gridRatio = 1.0;
  90137. /**
  90138. * Allows setting an offset for the grid lines.
  90139. */
  90140. _this.gridOffset = BABYLON.Vector3.Zero();
  90141. /**
  90142. * The frequency of thicker lines.
  90143. */
  90144. _this.majorUnitFrequency = 10;
  90145. /**
  90146. * The visibility of minor units in the grid.
  90147. */
  90148. _this.minorUnitVisibility = 0.33;
  90149. /**
  90150. * The grid opacity outside of the lines.
  90151. */
  90152. _this.opacity = 1.0;
  90153. /**
  90154. * Determine RBG output is premultiplied by alpha value.
  90155. */
  90156. _this.preMultiplyAlpha = false;
  90157. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  90158. return _this;
  90159. }
  90160. /**
  90161. * Returns wehter or not the grid requires alpha blending.
  90162. */
  90163. GridMaterial.prototype.needAlphaBlending = function () {
  90164. return this.opacity < 1.0;
  90165. };
  90166. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  90167. return this.needAlphaBlending();
  90168. };
  90169. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90170. if (this.isFrozen) {
  90171. if (this._wasPreviouslyReady && subMesh.effect) {
  90172. return true;
  90173. }
  90174. }
  90175. if (!subMesh._materialDefines) {
  90176. subMesh._materialDefines = new GridMaterialDefines();
  90177. }
  90178. var defines = subMesh._materialDefines;
  90179. var scene = this.getScene();
  90180. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90181. if (this._renderId === scene.getRenderId()) {
  90182. return true;
  90183. }
  90184. }
  90185. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  90186. defines.TRANSPARENT = !defines.TRANSPARENT;
  90187. defines.markAsUnprocessed();
  90188. }
  90189. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  90190. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  90191. defines.markAsUnprocessed();
  90192. }
  90193. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  90194. // Get correct effect
  90195. if (defines.isDirty) {
  90196. defines.markAsProcessed();
  90197. scene.resetCachedMaterial();
  90198. // Attributes
  90199. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90200. // Defines
  90201. var join = defines.toString();
  90202. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  90203. }
  90204. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90205. return false;
  90206. }
  90207. this._renderId = scene.getRenderId();
  90208. this._wasPreviouslyReady = true;
  90209. return true;
  90210. };
  90211. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90212. var scene = this.getScene();
  90213. var defines = subMesh._materialDefines;
  90214. if (!defines) {
  90215. return;
  90216. }
  90217. var effect = subMesh.effect;
  90218. if (!effect) {
  90219. return;
  90220. }
  90221. this._activeEffect = effect;
  90222. // Matrices
  90223. this.bindOnlyWorldMatrix(world);
  90224. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  90225. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  90226. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  90227. // Uniforms
  90228. if (this._mustRebind(scene, effect)) {
  90229. this._activeEffect.setColor3("mainColor", this.mainColor);
  90230. this._activeEffect.setColor3("lineColor", this.lineColor);
  90231. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  90232. this._gridControl.x = this.gridRatio;
  90233. this._gridControl.y = Math.round(this.majorUnitFrequency);
  90234. this._gridControl.z = this.minorUnitVisibility;
  90235. this._gridControl.w = this.opacity;
  90236. this._activeEffect.setVector4("gridControl", this._gridControl);
  90237. }
  90238. // Fog
  90239. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90240. this._afterBind(mesh, this._activeEffect);
  90241. };
  90242. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  90243. _super.prototype.dispose.call(this, forceDisposeEffect);
  90244. };
  90245. GridMaterial.prototype.clone = function (name) {
  90246. var _this = this;
  90247. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  90248. };
  90249. GridMaterial.prototype.serialize = function () {
  90250. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90251. serializationObject.customType = "BABYLON.GridMaterial";
  90252. return serializationObject;
  90253. };
  90254. GridMaterial.prototype.getClassName = function () {
  90255. return "GridMaterial";
  90256. };
  90257. GridMaterial.Parse = function (source, scene, rootUrl) {
  90258. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  90259. };
  90260. __decorate([
  90261. BABYLON.serializeAsColor3()
  90262. ], GridMaterial.prototype, "mainColor", void 0);
  90263. __decorate([
  90264. BABYLON.serializeAsColor3()
  90265. ], GridMaterial.prototype, "lineColor", void 0);
  90266. __decorate([
  90267. BABYLON.serialize()
  90268. ], GridMaterial.prototype, "gridRatio", void 0);
  90269. __decorate([
  90270. BABYLON.serializeAsColor3()
  90271. ], GridMaterial.prototype, "gridOffset", void 0);
  90272. __decorate([
  90273. BABYLON.serialize()
  90274. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  90275. __decorate([
  90276. BABYLON.serialize()
  90277. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  90278. __decorate([
  90279. BABYLON.serialize()
  90280. ], GridMaterial.prototype, "opacity", void 0);
  90281. __decorate([
  90282. BABYLON.serialize()
  90283. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  90284. return GridMaterial;
  90285. }(BABYLON.PushMaterial));
  90286. BABYLON.GridMaterial = GridMaterial;
  90287. })(BABYLON || (BABYLON = {}));
  90288. //# sourceMappingURL=babylon.gridmaterial.js.map
  90289. 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}";
  90290. 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}";
  90291. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90292. var BABYLON;
  90293. (function (BABYLON) {
  90294. var GLTFLoaderCoordinateSystemMode;
  90295. (function (GLTFLoaderCoordinateSystemMode) {
  90296. /**
  90297. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  90298. */
  90299. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  90300. /**
  90301. * Sets the useRightHandedSystem flag on the scene.
  90302. */
  90303. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  90304. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  90305. var GLTFLoaderAnimationStartMode;
  90306. (function (GLTFLoaderAnimationStartMode) {
  90307. /**
  90308. * No animation will start.
  90309. */
  90310. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  90311. /**
  90312. * The first animation will start.
  90313. */
  90314. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  90315. /**
  90316. * All animations will start.
  90317. */
  90318. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  90319. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  90320. var GLTFLoaderState;
  90321. (function (GLTFLoaderState) {
  90322. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  90323. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  90324. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  90325. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  90326. var GLTFFileLoader = /** @class */ (function () {
  90327. function GLTFFileLoader() {
  90328. // #region Common options
  90329. /**
  90330. * Raised when the asset has been parsed.
  90331. * The data.json property stores the glTF JSON.
  90332. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  90333. */
  90334. this.onParsedObservable = new BABYLON.Observable();
  90335. // #endregion
  90336. // #region V2 options
  90337. /**
  90338. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  90339. */
  90340. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  90341. /**
  90342. * The animation start mode (NONE, FIRST, ALL).
  90343. */
  90344. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  90345. /**
  90346. * Set to true to compile materials before raising the success callback.
  90347. */
  90348. this.compileMaterials = false;
  90349. /**
  90350. * Set to true to also compile materials with clip planes.
  90351. */
  90352. this.useClipPlane = false;
  90353. /**
  90354. * Set to true to compile shadow generators before raising the success callback.
  90355. */
  90356. this.compileShadowGenerators = false;
  90357. /**
  90358. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  90359. */
  90360. this.onMeshLoadedObservable = new BABYLON.Observable();
  90361. /**
  90362. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  90363. */
  90364. this.onTextureLoadedObservable = new BABYLON.Observable();
  90365. /**
  90366. * Raised when the loader creates a material after parsing the glTF properties of the material.
  90367. */
  90368. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90369. /**
  90370. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  90371. */
  90372. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  90373. /**
  90374. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  90375. * For assets with LODs, raised when all of the LODs are complete.
  90376. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  90377. */
  90378. this.onCompleteObservable = new BABYLON.Observable();
  90379. /**
  90380. * Raised when the loader is disposed.
  90381. */
  90382. this.onDisposeObservable = new BABYLON.Observable();
  90383. /**
  90384. * Raised after a loader extension is created.
  90385. * Set additional options for a loader extension in this event.
  90386. */
  90387. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90388. // #endregion
  90389. this._loader = null;
  90390. this.name = "gltf";
  90391. this.extensions = {
  90392. ".gltf": { isBinary: false },
  90393. ".glb": { isBinary: true }
  90394. };
  90395. }
  90396. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  90397. set: function (callback) {
  90398. if (this._onParsedObserver) {
  90399. this.onParsedObservable.remove(this._onParsedObserver);
  90400. }
  90401. this._onParsedObserver = this.onParsedObservable.add(callback);
  90402. },
  90403. enumerable: true,
  90404. configurable: true
  90405. });
  90406. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  90407. set: function (callback) {
  90408. if (this._onMeshLoadedObserver) {
  90409. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  90410. }
  90411. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  90412. },
  90413. enumerable: true,
  90414. configurable: true
  90415. });
  90416. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  90417. set: function (callback) {
  90418. if (this._onTextureLoadedObserver) {
  90419. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  90420. }
  90421. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  90422. },
  90423. enumerable: true,
  90424. configurable: true
  90425. });
  90426. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  90427. set: function (callback) {
  90428. if (this._onMaterialLoadedObserver) {
  90429. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  90430. }
  90431. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  90432. },
  90433. enumerable: true,
  90434. configurable: true
  90435. });
  90436. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  90437. set: function (callback) {
  90438. if (this._onAnimationGroupLoadedObserver) {
  90439. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  90440. }
  90441. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  90442. },
  90443. enumerable: true,
  90444. configurable: true
  90445. });
  90446. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  90447. set: function (callback) {
  90448. if (this._onCompleteObserver) {
  90449. this.onCompleteObservable.remove(this._onCompleteObserver);
  90450. }
  90451. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  90452. },
  90453. enumerable: true,
  90454. configurable: true
  90455. });
  90456. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  90457. set: function (callback) {
  90458. if (this._onDisposeObserver) {
  90459. this.onDisposeObservable.remove(this._onDisposeObserver);
  90460. }
  90461. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  90462. },
  90463. enumerable: true,
  90464. configurable: true
  90465. });
  90466. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  90467. set: function (callback) {
  90468. if (this._onExtensionLoadedObserver) {
  90469. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  90470. }
  90471. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  90472. },
  90473. enumerable: true,
  90474. configurable: true
  90475. });
  90476. /**
  90477. * Gets a promise that resolves when the asset is completely loaded.
  90478. * @returns A promise that resolves when the asset is completely loaded.
  90479. */
  90480. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  90481. var _this = this;
  90482. return new Promise(function (resolve) {
  90483. _this.onCompleteObservable.add(function () {
  90484. resolve();
  90485. }, undefined, undefined, undefined, true);
  90486. });
  90487. };
  90488. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  90489. /**
  90490. * The loader state or null if not active.
  90491. */
  90492. get: function () {
  90493. return this._loader ? this._loader.state : null;
  90494. },
  90495. enumerable: true,
  90496. configurable: true
  90497. });
  90498. /**
  90499. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  90500. */
  90501. GLTFFileLoader.prototype.dispose = function () {
  90502. if (this._loader) {
  90503. this._loader.dispose();
  90504. this._loader = null;
  90505. }
  90506. this.onMeshLoadedObservable.clear();
  90507. this.onTextureLoadedObservable.clear();
  90508. this.onMaterialLoadedObservable.clear();
  90509. this.onDisposeObservable.notifyObservers(this);
  90510. this.onDisposeObservable.clear();
  90511. };
  90512. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90513. var _this = this;
  90514. return Promise.resolve().then(function () {
  90515. var loaderData = _this._parse(data);
  90516. _this._loader = _this._getLoader(loaderData);
  90517. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  90518. });
  90519. };
  90520. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90521. var _this = this;
  90522. return Promise.resolve().then(function () {
  90523. var loaderData = _this._parse(data);
  90524. _this._loader = _this._getLoader(loaderData);
  90525. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  90526. });
  90527. };
  90528. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  90529. var _this = this;
  90530. return Promise.resolve().then(function () {
  90531. var loaderData = _this._parse(data);
  90532. _this._loader = _this._getLoader(loaderData);
  90533. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  90534. var container = new BABYLON.AssetContainer(scene);
  90535. Array.prototype.push.apply(container.meshes, result.meshes);
  90536. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  90537. Array.prototype.push.apply(container.skeletons, result.skeletons);
  90538. container.removeAllFromScene();
  90539. return container;
  90540. });
  90541. });
  90542. };
  90543. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  90544. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  90545. };
  90546. GLTFFileLoader.prototype.createPlugin = function () {
  90547. return new GLTFFileLoader();
  90548. };
  90549. GLTFFileLoader.prototype._parse = function (data) {
  90550. var parsedData;
  90551. if (data instanceof ArrayBuffer) {
  90552. parsedData = GLTFFileLoader._parseBinary(data);
  90553. }
  90554. else {
  90555. parsedData = {
  90556. json: JSON.parse(data),
  90557. bin: null
  90558. };
  90559. }
  90560. this.onParsedObservable.notifyObservers(parsedData);
  90561. this.onParsedObservable.clear();
  90562. return parsedData;
  90563. };
  90564. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  90565. var _this = this;
  90566. var loaderVersion = { major: 2, minor: 0 };
  90567. var asset = loaderData.json.asset || {};
  90568. var version = GLTFFileLoader._parseVersion(asset.version);
  90569. if (!version) {
  90570. throw new Error("Invalid version: " + asset.version);
  90571. }
  90572. if (asset.minVersion !== undefined) {
  90573. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  90574. if (!minVersion) {
  90575. throw new Error("Invalid minimum version: " + asset.minVersion);
  90576. }
  90577. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  90578. throw new Error("Incompatible minimum version: " + asset.minVersion);
  90579. }
  90580. }
  90581. var createLoaders = {
  90582. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  90583. 2: GLTFFileLoader.CreateGLTFLoaderV2
  90584. };
  90585. var createLoader = createLoaders[version.major];
  90586. if (!createLoader) {
  90587. throw new Error("Unsupported version: " + asset.version);
  90588. }
  90589. var loader = createLoader();
  90590. loader.coordinateSystemMode = this.coordinateSystemMode;
  90591. loader.animationStartMode = this.animationStartMode;
  90592. loader.compileMaterials = this.compileMaterials;
  90593. loader.useClipPlane = this.useClipPlane;
  90594. loader.compileShadowGenerators = this.compileShadowGenerators;
  90595. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  90596. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  90597. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  90598. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  90599. loader.onCompleteObservable.add(function () {
  90600. _this.onMeshLoadedObservable.clear();
  90601. _this.onTextureLoadedObservable.clear();
  90602. _this.onMaterialLoadedObservable.clear();
  90603. _this.onCompleteObservable.notifyObservers(_this);
  90604. _this.onCompleteObservable.clear();
  90605. });
  90606. return loader;
  90607. };
  90608. GLTFFileLoader._parseBinary = function (data) {
  90609. var Binary = {
  90610. Magic: 0x46546C67
  90611. };
  90612. var binaryReader = new BinaryReader(data);
  90613. var magic = binaryReader.readUint32();
  90614. if (magic !== Binary.Magic) {
  90615. throw new Error("Unexpected magic: " + magic);
  90616. }
  90617. var version = binaryReader.readUint32();
  90618. switch (version) {
  90619. case 1: return GLTFFileLoader._parseV1(binaryReader);
  90620. case 2: return GLTFFileLoader._parseV2(binaryReader);
  90621. }
  90622. throw new Error("Unsupported version: " + version);
  90623. };
  90624. GLTFFileLoader._parseV1 = function (binaryReader) {
  90625. var ContentFormat = {
  90626. JSON: 0
  90627. };
  90628. var length = binaryReader.readUint32();
  90629. if (length != binaryReader.getLength()) {
  90630. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90631. }
  90632. var contentLength = binaryReader.readUint32();
  90633. var contentFormat = binaryReader.readUint32();
  90634. var content;
  90635. switch (contentFormat) {
  90636. case ContentFormat.JSON: {
  90637. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  90638. break;
  90639. }
  90640. default: {
  90641. throw new Error("Unexpected content format: " + contentFormat);
  90642. }
  90643. }
  90644. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  90645. var body = binaryReader.readUint8Array(bytesRemaining);
  90646. return {
  90647. json: content,
  90648. bin: body
  90649. };
  90650. };
  90651. GLTFFileLoader._parseV2 = function (binaryReader) {
  90652. var ChunkFormat = {
  90653. JSON: 0x4E4F534A,
  90654. BIN: 0x004E4942
  90655. };
  90656. var length = binaryReader.readUint32();
  90657. if (length !== binaryReader.getLength()) {
  90658. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90659. }
  90660. // JSON chunk
  90661. var chunkLength = binaryReader.readUint32();
  90662. var chunkFormat = binaryReader.readUint32();
  90663. if (chunkFormat !== ChunkFormat.JSON) {
  90664. throw new Error("First chunk format is not JSON");
  90665. }
  90666. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  90667. // Look for BIN chunk
  90668. var bin = null;
  90669. while (binaryReader.getPosition() < binaryReader.getLength()) {
  90670. var chunkLength_1 = binaryReader.readUint32();
  90671. var chunkFormat_1 = binaryReader.readUint32();
  90672. switch (chunkFormat_1) {
  90673. case ChunkFormat.JSON: {
  90674. throw new Error("Unexpected JSON chunk");
  90675. }
  90676. case ChunkFormat.BIN: {
  90677. bin = binaryReader.readUint8Array(chunkLength_1);
  90678. break;
  90679. }
  90680. default: {
  90681. // ignore unrecognized chunkFormat
  90682. binaryReader.skipBytes(chunkLength_1);
  90683. break;
  90684. }
  90685. }
  90686. }
  90687. return {
  90688. json: json,
  90689. bin: bin
  90690. };
  90691. };
  90692. GLTFFileLoader._parseVersion = function (version) {
  90693. if (version === "1.0" || version === "1.0.1") {
  90694. return {
  90695. major: 1,
  90696. minor: 0
  90697. };
  90698. }
  90699. var match = (version + "").match(/^(\d+)\.(\d+)/);
  90700. if (!match) {
  90701. return null;
  90702. }
  90703. return {
  90704. major: parseInt(match[1]),
  90705. minor: parseInt(match[2])
  90706. };
  90707. };
  90708. GLTFFileLoader._compareVersion = function (a, b) {
  90709. if (a.major > b.major)
  90710. return 1;
  90711. if (a.major < b.major)
  90712. return -1;
  90713. if (a.minor > b.minor)
  90714. return 1;
  90715. if (a.minor < b.minor)
  90716. return -1;
  90717. return 0;
  90718. };
  90719. GLTFFileLoader._decodeBufferToText = function (buffer) {
  90720. var result = "";
  90721. var length = buffer.byteLength;
  90722. for (var i = 0; i < length; i++) {
  90723. result += String.fromCharCode(buffer[i]);
  90724. }
  90725. return result;
  90726. };
  90727. // #endregion
  90728. // #region V1 options
  90729. GLTFFileLoader.IncrementalLoading = true;
  90730. GLTFFileLoader.HomogeneousCoordinates = false;
  90731. return GLTFFileLoader;
  90732. }());
  90733. BABYLON.GLTFFileLoader = GLTFFileLoader;
  90734. var BinaryReader = /** @class */ (function () {
  90735. function BinaryReader(arrayBuffer) {
  90736. this._arrayBuffer = arrayBuffer;
  90737. this._dataView = new DataView(arrayBuffer);
  90738. this._byteOffset = 0;
  90739. }
  90740. BinaryReader.prototype.getPosition = function () {
  90741. return this._byteOffset;
  90742. };
  90743. BinaryReader.prototype.getLength = function () {
  90744. return this._arrayBuffer.byteLength;
  90745. };
  90746. BinaryReader.prototype.readUint32 = function () {
  90747. var value = this._dataView.getUint32(this._byteOffset, true);
  90748. this._byteOffset += 4;
  90749. return value;
  90750. };
  90751. BinaryReader.prototype.readUint8Array = function (length) {
  90752. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  90753. this._byteOffset += length;
  90754. return value;
  90755. };
  90756. BinaryReader.prototype.skipBytes = function (length) {
  90757. this._byteOffset += length;
  90758. };
  90759. return BinaryReader;
  90760. }());
  90761. if (BABYLON.SceneLoader) {
  90762. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  90763. }
  90764. })(BABYLON || (BABYLON = {}));
  90765. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  90766. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90767. var BABYLON;
  90768. (function (BABYLON) {
  90769. var GLTF1;
  90770. (function (GLTF1) {
  90771. /**
  90772. * Enums
  90773. */
  90774. var EComponentType;
  90775. (function (EComponentType) {
  90776. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  90777. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90778. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  90779. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90780. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  90781. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  90782. var EShaderType;
  90783. (function (EShaderType) {
  90784. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  90785. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  90786. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  90787. var EParameterType;
  90788. (function (EParameterType) {
  90789. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90790. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90791. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90792. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90793. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90794. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90795. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90796. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90797. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90798. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90799. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90800. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90801. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90802. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90803. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90804. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90805. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90806. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90807. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90808. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90809. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90810. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90811. var ETextureWrapMode;
  90812. (function (ETextureWrapMode) {
  90813. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90814. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90815. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90816. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90817. var ETextureFilterType;
  90818. (function (ETextureFilterType) {
  90819. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90820. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90821. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90822. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90823. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90824. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90825. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90826. var ETextureFormat;
  90827. (function (ETextureFormat) {
  90828. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90829. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90830. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90831. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90832. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90833. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90834. var ECullingType;
  90835. (function (ECullingType) {
  90836. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90837. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90838. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90839. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90840. var EBlendingFunction;
  90841. (function (EBlendingFunction) {
  90842. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90843. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90844. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90845. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90846. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90847. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90848. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90849. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90850. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90851. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90852. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90853. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90854. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90855. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90856. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90857. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90858. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90859. })(BABYLON || (BABYLON = {}));
  90860. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90861. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90862. var BABYLON;
  90863. (function (BABYLON) {
  90864. var GLTF1;
  90865. (function (GLTF1) {
  90866. /**
  90867. * Tokenizer. Used for shaders compatibility
  90868. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90869. */
  90870. var ETokenType;
  90871. (function (ETokenType) {
  90872. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90873. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90874. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90875. })(ETokenType || (ETokenType = {}));
  90876. var Tokenizer = /** @class */ (function () {
  90877. function Tokenizer(toParse) {
  90878. this._pos = 0;
  90879. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90880. this._toParse = toParse;
  90881. this._maxPos = toParse.length;
  90882. }
  90883. Tokenizer.prototype.getNextToken = function () {
  90884. if (this.isEnd())
  90885. return ETokenType.END_OF_INPUT;
  90886. this.currentString = this.read();
  90887. this.currentToken = ETokenType.UNKNOWN;
  90888. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90889. this.currentToken = ETokenType.IDENTIFIER;
  90890. this.currentIdentifier = this.currentString;
  90891. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90892. this.currentIdentifier += this.currentString;
  90893. this.forward();
  90894. }
  90895. }
  90896. return this.currentToken;
  90897. };
  90898. Tokenizer.prototype.peek = function () {
  90899. return this._toParse[this._pos];
  90900. };
  90901. Tokenizer.prototype.read = function () {
  90902. return this._toParse[this._pos++];
  90903. };
  90904. Tokenizer.prototype.forward = function () {
  90905. this._pos++;
  90906. };
  90907. Tokenizer.prototype.isEnd = function () {
  90908. return this._pos >= this._maxPos;
  90909. };
  90910. return Tokenizer;
  90911. }());
  90912. /**
  90913. * Values
  90914. */
  90915. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90916. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90917. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90918. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90919. /**
  90920. * Parse
  90921. */
  90922. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90923. for (var buf in parsedBuffers) {
  90924. var parsedBuffer = parsedBuffers[buf];
  90925. gltfRuntime.buffers[buf] = parsedBuffer;
  90926. gltfRuntime.buffersCount++;
  90927. }
  90928. };
  90929. var parseShaders = function (parsedShaders, gltfRuntime) {
  90930. for (var sha in parsedShaders) {
  90931. var parsedShader = parsedShaders[sha];
  90932. gltfRuntime.shaders[sha] = parsedShader;
  90933. gltfRuntime.shaderscount++;
  90934. }
  90935. };
  90936. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90937. for (var object in parsedObjects) {
  90938. var parsedObject = parsedObjects[object];
  90939. gltfRuntime[runtimeProperty][object] = parsedObject;
  90940. }
  90941. };
  90942. /**
  90943. * Utils
  90944. */
  90945. var normalizeUVs = function (buffer) {
  90946. if (!buffer) {
  90947. return;
  90948. }
  90949. for (var i = 0; i < buffer.length / 2; i++) {
  90950. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90951. }
  90952. };
  90953. var getAttribute = function (attributeParameter) {
  90954. if (attributeParameter.semantic === "NORMAL") {
  90955. return "normal";
  90956. }
  90957. else if (attributeParameter.semantic === "POSITION") {
  90958. return "position";
  90959. }
  90960. else if (attributeParameter.semantic === "JOINT") {
  90961. return "matricesIndices";
  90962. }
  90963. else if (attributeParameter.semantic === "WEIGHT") {
  90964. return "matricesWeights";
  90965. }
  90966. else if (attributeParameter.semantic === "COLOR") {
  90967. return "color";
  90968. }
  90969. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90970. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90971. return "uv" + (channel === 0 ? "" : channel + 1);
  90972. }
  90973. return null;
  90974. };
  90975. /**
  90976. * Loads and creates animations
  90977. */
  90978. var loadAnimations = function (gltfRuntime) {
  90979. for (var anim in gltfRuntime.animations) {
  90980. var animation = gltfRuntime.animations[anim];
  90981. if (!animation.channels || !animation.samplers) {
  90982. continue;
  90983. }
  90984. var lastAnimation = null;
  90985. for (var i = 0; i < animation.channels.length; i++) {
  90986. // Get parameters and load buffers
  90987. var channel = animation.channels[i];
  90988. var sampler = animation.samplers[channel.sampler];
  90989. if (!sampler) {
  90990. continue;
  90991. }
  90992. var inputData = null;
  90993. var outputData = null;
  90994. if (animation.parameters) {
  90995. inputData = animation.parameters[sampler.input];
  90996. outputData = animation.parameters[sampler.output];
  90997. }
  90998. else {
  90999. inputData = sampler.input;
  91000. outputData = sampler.output;
  91001. }
  91002. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  91003. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  91004. var targetID = channel.target.id;
  91005. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  91006. if (targetNode === null) {
  91007. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  91008. }
  91009. if (targetNode === null) {
  91010. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  91011. continue;
  91012. }
  91013. var isBone = targetNode instanceof BABYLON.Bone;
  91014. // Get target path (position, rotation or scaling)
  91015. var targetPath = channel.target.path;
  91016. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  91017. if (targetPathIndex !== -1) {
  91018. targetPath = babylonAnimationPaths[targetPathIndex];
  91019. }
  91020. // Determine animation type
  91021. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  91022. if (!isBone) {
  91023. if (targetPath === "rotationQuaternion") {
  91024. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91025. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  91026. }
  91027. else {
  91028. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91029. }
  91030. }
  91031. // Create animation and key frames
  91032. var babylonAnimation = null;
  91033. var keys = [];
  91034. var arrayOffset = 0;
  91035. var modifyKey = false;
  91036. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  91037. babylonAnimation = lastAnimation;
  91038. modifyKey = true;
  91039. }
  91040. if (!modifyKey) {
  91041. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91042. }
  91043. // For each frame
  91044. for (var j = 0; j < bufferInput.length; j++) {
  91045. var value = null;
  91046. if (targetPath === "rotationQuaternion") {
  91047. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  91048. arrayOffset += 4;
  91049. }
  91050. else {
  91051. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  91052. arrayOffset += 3;
  91053. }
  91054. if (isBone) {
  91055. var bone = targetNode;
  91056. var translation = BABYLON.Vector3.Zero();
  91057. var rotationQuaternion = new BABYLON.Quaternion();
  91058. var scaling = BABYLON.Vector3.Zero();
  91059. // Warning on decompose
  91060. var mat = bone.getBaseMatrix();
  91061. if (modifyKey && lastAnimation) {
  91062. mat = lastAnimation.getKeys()[j].value;
  91063. }
  91064. mat.decompose(scaling, rotationQuaternion, translation);
  91065. if (targetPath === "position") {
  91066. translation = value;
  91067. }
  91068. else if (targetPath === "rotationQuaternion") {
  91069. rotationQuaternion = value;
  91070. }
  91071. else {
  91072. scaling = value;
  91073. }
  91074. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  91075. }
  91076. if (!modifyKey) {
  91077. keys.push({
  91078. frame: bufferInput[j],
  91079. value: value
  91080. });
  91081. }
  91082. else if (lastAnimation) {
  91083. lastAnimation.getKeys()[j].value = value;
  91084. }
  91085. }
  91086. // Finish
  91087. if (!modifyKey && babylonAnimation) {
  91088. babylonAnimation.setKeys(keys);
  91089. targetNode.animations.push(babylonAnimation);
  91090. }
  91091. lastAnimation = babylonAnimation;
  91092. gltfRuntime.scene.stopAnimation(targetNode);
  91093. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  91094. }
  91095. }
  91096. };
  91097. /**
  91098. * Returns the bones transformation matrix
  91099. */
  91100. var configureBoneTransformation = function (node) {
  91101. var mat = null;
  91102. if (node.translation || node.rotation || node.scale) {
  91103. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  91104. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  91105. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  91106. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  91107. }
  91108. else {
  91109. mat = BABYLON.Matrix.FromArray(node.matrix);
  91110. }
  91111. return mat;
  91112. };
  91113. /**
  91114. * Returns the parent bone
  91115. */
  91116. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  91117. // Try to find
  91118. for (var i = 0; i < newSkeleton.bones.length; i++) {
  91119. if (newSkeleton.bones[i].name === jointName) {
  91120. return newSkeleton.bones[i];
  91121. }
  91122. }
  91123. // Not found, search in gltf nodes
  91124. var nodes = gltfRuntime.nodes;
  91125. for (var nde in nodes) {
  91126. var node = nodes[nde];
  91127. if (!node.jointName) {
  91128. continue;
  91129. }
  91130. var children = node.children;
  91131. for (var i = 0; i < children.length; i++) {
  91132. var child = gltfRuntime.nodes[children[i]];
  91133. if (!child.jointName) {
  91134. continue;
  91135. }
  91136. if (child.jointName === jointName) {
  91137. var mat = configureBoneTransformation(node);
  91138. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  91139. bone.id = nde;
  91140. return bone;
  91141. }
  91142. }
  91143. }
  91144. return null;
  91145. };
  91146. /**
  91147. * Returns the appropriate root node
  91148. */
  91149. var getNodeToRoot = function (nodesToRoot, id) {
  91150. for (var i = 0; i < nodesToRoot.length; i++) {
  91151. var nodeToRoot = nodesToRoot[i];
  91152. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  91153. var child = nodeToRoot.node.children[j];
  91154. if (child === id) {
  91155. return nodeToRoot.bone;
  91156. }
  91157. }
  91158. }
  91159. return null;
  91160. };
  91161. /**
  91162. * Returns the node with the joint name
  91163. */
  91164. var getJointNode = function (gltfRuntime, jointName) {
  91165. var nodes = gltfRuntime.nodes;
  91166. var node = nodes[jointName];
  91167. if (node) {
  91168. return {
  91169. node: node,
  91170. id: jointName
  91171. };
  91172. }
  91173. for (var nde in nodes) {
  91174. node = nodes[nde];
  91175. if (node.jointName === jointName) {
  91176. return {
  91177. node: node,
  91178. id: nde
  91179. };
  91180. }
  91181. }
  91182. return null;
  91183. };
  91184. /**
  91185. * Checks if a nodes is in joints
  91186. */
  91187. var nodeIsInJoints = function (skins, id) {
  91188. for (var i = 0; i < skins.jointNames.length; i++) {
  91189. if (skins.jointNames[i] === id) {
  91190. return true;
  91191. }
  91192. }
  91193. return false;
  91194. };
  91195. /**
  91196. * Fills the nodes to root for bones and builds hierarchy
  91197. */
  91198. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  91199. // Creates nodes for root
  91200. for (var nde in gltfRuntime.nodes) {
  91201. var node = gltfRuntime.nodes[nde];
  91202. var id = nde;
  91203. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  91204. continue;
  91205. }
  91206. // Create node to root bone
  91207. var mat = configureBoneTransformation(node);
  91208. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  91209. bone.id = id;
  91210. nodesToRoot.push({ bone: bone, node: node, id: id });
  91211. }
  91212. // Parenting
  91213. for (var i = 0; i < nodesToRoot.length; i++) {
  91214. var nodeToRoot = nodesToRoot[i];
  91215. var children = nodeToRoot.node.children;
  91216. for (var j = 0; j < children.length; j++) {
  91217. var child = null;
  91218. for (var k = 0; k < nodesToRoot.length; k++) {
  91219. if (nodesToRoot[k].id === children[j]) {
  91220. child = nodesToRoot[k];
  91221. break;
  91222. }
  91223. }
  91224. if (child) {
  91225. child.bone._parent = nodeToRoot.bone;
  91226. nodeToRoot.bone.children.push(child.bone);
  91227. }
  91228. }
  91229. }
  91230. };
  91231. /**
  91232. * Imports a skeleton
  91233. */
  91234. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  91235. if (!newSkeleton) {
  91236. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  91237. }
  91238. if (!skins.babylonSkeleton) {
  91239. return newSkeleton;
  91240. }
  91241. // Find the root bones
  91242. var nodesToRoot = [];
  91243. var nodesToRootToAdd = [];
  91244. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  91245. newSkeleton.bones = [];
  91246. // Joints
  91247. for (var i = 0; i < skins.jointNames.length; i++) {
  91248. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91249. if (!jointNode) {
  91250. continue;
  91251. }
  91252. var node = jointNode.node;
  91253. if (!node) {
  91254. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  91255. continue;
  91256. }
  91257. var id = jointNode.id;
  91258. // Optimize, if the bone already exists...
  91259. var existingBone = gltfRuntime.scene.getBoneByID(id);
  91260. if (existingBone) {
  91261. newSkeleton.bones.push(existingBone);
  91262. continue;
  91263. }
  91264. // Search for parent bone
  91265. var foundBone = false;
  91266. var parentBone = null;
  91267. for (var j = 0; j < i; j++) {
  91268. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  91269. if (!jointNode_1) {
  91270. continue;
  91271. }
  91272. var joint = jointNode_1.node;
  91273. if (!joint) {
  91274. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  91275. continue;
  91276. }
  91277. var children = joint.children;
  91278. if (!children) {
  91279. continue;
  91280. }
  91281. foundBone = false;
  91282. for (var k = 0; k < children.length; k++) {
  91283. if (children[k] === id) {
  91284. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  91285. foundBone = true;
  91286. break;
  91287. }
  91288. }
  91289. if (foundBone) {
  91290. break;
  91291. }
  91292. }
  91293. // Create bone
  91294. var mat = configureBoneTransformation(node);
  91295. if (!parentBone && nodesToRoot.length > 0) {
  91296. parentBone = getNodeToRoot(nodesToRoot, id);
  91297. if (parentBone) {
  91298. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  91299. nodesToRootToAdd.push(parentBone);
  91300. }
  91301. }
  91302. }
  91303. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  91304. bone.id = id;
  91305. }
  91306. // Polish
  91307. var bones = newSkeleton.bones;
  91308. newSkeleton.bones = [];
  91309. for (var i = 0; i < skins.jointNames.length; i++) {
  91310. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91311. if (!jointNode) {
  91312. continue;
  91313. }
  91314. for (var j = 0; j < bones.length; j++) {
  91315. if (bones[j].id === jointNode.id) {
  91316. newSkeleton.bones.push(bones[j]);
  91317. break;
  91318. }
  91319. }
  91320. }
  91321. newSkeleton.prepare();
  91322. // Finish
  91323. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  91324. newSkeleton.bones.push(nodesToRootToAdd[i]);
  91325. }
  91326. return newSkeleton;
  91327. };
  91328. /**
  91329. * Imports a mesh and its geometries
  91330. */
  91331. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  91332. if (!newMesh) {
  91333. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91334. newMesh.id = id;
  91335. }
  91336. if (!node.babylonNode) {
  91337. return newMesh;
  91338. }
  91339. var subMaterials = [];
  91340. var vertexData = null;
  91341. var verticesStarts = new Array();
  91342. var verticesCounts = new Array();
  91343. var indexStarts = new Array();
  91344. var indexCounts = new Array();
  91345. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91346. var meshID = meshes[meshIndex];
  91347. var mesh = gltfRuntime.meshes[meshID];
  91348. if (!mesh) {
  91349. continue;
  91350. }
  91351. // Positions, normals and UVs
  91352. for (var i = 0; i < mesh.primitives.length; i++) {
  91353. // Temporary vertex data
  91354. var tempVertexData = new BABYLON.VertexData();
  91355. var primitive = mesh.primitives[i];
  91356. if (primitive.mode !== 4) {
  91357. // continue;
  91358. }
  91359. var attributes = primitive.attributes;
  91360. var accessor = null;
  91361. var buffer = null;
  91362. // Set positions, normal and uvs
  91363. for (var semantic in attributes) {
  91364. // Link accessor and buffer view
  91365. accessor = gltfRuntime.accessors[attributes[semantic]];
  91366. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91367. if (semantic === "NORMAL") {
  91368. tempVertexData.normals = new Float32Array(buffer.length);
  91369. tempVertexData.normals.set(buffer);
  91370. }
  91371. else if (semantic === "POSITION") {
  91372. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  91373. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  91374. for (var j = 0; j < buffer.length; j += 4) {
  91375. tempVertexData.positions[j] = buffer[j];
  91376. tempVertexData.positions[j + 1] = buffer[j + 1];
  91377. tempVertexData.positions[j + 2] = buffer[j + 2];
  91378. }
  91379. }
  91380. else {
  91381. tempVertexData.positions = new Float32Array(buffer.length);
  91382. tempVertexData.positions.set(buffer);
  91383. }
  91384. verticesCounts.push(tempVertexData.positions.length);
  91385. }
  91386. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  91387. var channel = Number(semantic.split("_")[1]);
  91388. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  91389. var uvs = new Float32Array(buffer.length);
  91390. uvs.set(buffer);
  91391. normalizeUVs(uvs);
  91392. tempVertexData.set(uvs, uvKind);
  91393. }
  91394. else if (semantic === "JOINT") {
  91395. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  91396. tempVertexData.matricesIndices.set(buffer);
  91397. }
  91398. else if (semantic === "WEIGHT") {
  91399. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  91400. tempVertexData.matricesWeights.set(buffer);
  91401. }
  91402. else if (semantic === "COLOR") {
  91403. tempVertexData.colors = new Float32Array(buffer.length);
  91404. tempVertexData.colors.set(buffer);
  91405. }
  91406. }
  91407. // Indices
  91408. accessor = gltfRuntime.accessors[primitive.indices];
  91409. if (accessor) {
  91410. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91411. tempVertexData.indices = new Int32Array(buffer.length);
  91412. tempVertexData.indices.set(buffer);
  91413. indexCounts.push(tempVertexData.indices.length);
  91414. }
  91415. else {
  91416. // Set indices on the fly
  91417. var indices = [];
  91418. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  91419. indices.push(j);
  91420. }
  91421. tempVertexData.indices = new Int32Array(indices);
  91422. indexCounts.push(tempVertexData.indices.length);
  91423. }
  91424. if (!vertexData) {
  91425. vertexData = tempVertexData;
  91426. }
  91427. else {
  91428. vertexData.merge(tempVertexData);
  91429. }
  91430. // Sub material
  91431. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  91432. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  91433. // Update vertices start and index start
  91434. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  91435. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  91436. }
  91437. }
  91438. var material;
  91439. if (subMaterials.length > 1) {
  91440. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  91441. material.subMaterials = subMaterials;
  91442. }
  91443. else {
  91444. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  91445. }
  91446. if (subMaterials.length === 1) {
  91447. material = subMaterials[0];
  91448. }
  91449. if (!newMesh.material) {
  91450. newMesh.material = material;
  91451. }
  91452. // Apply geometry
  91453. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  91454. newMesh.computeWorldMatrix(true);
  91455. // Apply submeshes
  91456. newMesh.subMeshes = [];
  91457. var index = 0;
  91458. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91459. var meshID = meshes[meshIndex];
  91460. var mesh = gltfRuntime.meshes[meshID];
  91461. if (!mesh) {
  91462. continue;
  91463. }
  91464. for (var i = 0; i < mesh.primitives.length; i++) {
  91465. if (mesh.primitives[i].mode !== 4) {
  91466. //continue;
  91467. }
  91468. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  91469. index++;
  91470. }
  91471. }
  91472. // Finish
  91473. return newMesh;
  91474. };
  91475. /**
  91476. * Configure node transformation from position, rotation and scaling
  91477. */
  91478. var configureNode = function (newNode, position, rotation, scaling) {
  91479. if (newNode.position) {
  91480. newNode.position = position;
  91481. }
  91482. if (newNode.rotationQuaternion || newNode.rotation) {
  91483. newNode.rotationQuaternion = rotation;
  91484. }
  91485. if (newNode.scaling) {
  91486. newNode.scaling = scaling;
  91487. }
  91488. };
  91489. /**
  91490. * Configures node from transformation matrix
  91491. */
  91492. var configureNodeFromMatrix = function (newNode, node, parent) {
  91493. if (node.matrix) {
  91494. var position = new BABYLON.Vector3(0, 0, 0);
  91495. var rotation = new BABYLON.Quaternion();
  91496. var scaling = new BABYLON.Vector3(0, 0, 0);
  91497. var mat = BABYLON.Matrix.FromArray(node.matrix);
  91498. mat.decompose(scaling, rotation, position);
  91499. configureNode(newNode, position, rotation, scaling);
  91500. }
  91501. else if (node.translation && node.rotation && node.scale) {
  91502. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  91503. }
  91504. newNode.computeWorldMatrix(true);
  91505. };
  91506. /**
  91507. * Imports a node
  91508. */
  91509. var importNode = function (gltfRuntime, node, id, parent) {
  91510. var lastNode = null;
  91511. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  91512. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  91513. return null;
  91514. }
  91515. }
  91516. // Meshes
  91517. if (node.skin) {
  91518. if (node.meshes) {
  91519. var skin = gltfRuntime.skins[node.skin];
  91520. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  91521. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  91522. if (newMesh.skeleton === null) {
  91523. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  91524. if (!skin.babylonSkeleton) {
  91525. skin.babylonSkeleton = newMesh.skeleton;
  91526. }
  91527. }
  91528. lastNode = newMesh;
  91529. }
  91530. }
  91531. else if (node.meshes) {
  91532. /**
  91533. * Improve meshes property
  91534. */
  91535. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  91536. lastNode = newMesh;
  91537. }
  91538. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91539. var light = gltfRuntime.lights[node.light];
  91540. if (light) {
  91541. if (light.type === "ambient") {
  91542. var ambienLight = light[light.type];
  91543. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91544. hemiLight.name = node.name || "";
  91545. if (ambienLight.color) {
  91546. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  91547. }
  91548. lastNode = hemiLight;
  91549. }
  91550. else if (light.type === "directional") {
  91551. var directionalLight = light[light.type];
  91552. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91553. dirLight.name = node.name || "";
  91554. if (directionalLight.color) {
  91555. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  91556. }
  91557. lastNode = dirLight;
  91558. }
  91559. else if (light.type === "point") {
  91560. var pointLight = light[light.type];
  91561. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91562. ptLight.name = node.name || "";
  91563. if (pointLight.color) {
  91564. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  91565. }
  91566. lastNode = ptLight;
  91567. }
  91568. else if (light.type === "spot") {
  91569. var spotLight = light[light.type];
  91570. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  91571. spLight.name = node.name || "";
  91572. if (spotLight.color) {
  91573. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  91574. }
  91575. if (spotLight.fallOfAngle) {
  91576. spLight.angle = spotLight.fallOfAngle;
  91577. }
  91578. if (spotLight.fallOffExponent) {
  91579. spLight.exponent = spotLight.fallOffExponent;
  91580. }
  91581. lastNode = spLight;
  91582. }
  91583. }
  91584. }
  91585. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91586. var camera = gltfRuntime.cameras[node.camera];
  91587. if (camera) {
  91588. if (camera.type === "orthographic") {
  91589. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91590. orthoCamera.name = node.name || "";
  91591. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  91592. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91593. lastNode = orthoCamera;
  91594. }
  91595. else if (camera.type === "perspective") {
  91596. var perspectiveCamera = camera[camera.type];
  91597. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91598. persCamera.name = node.name || "";
  91599. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91600. if (!perspectiveCamera.aspectRatio) {
  91601. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  91602. }
  91603. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  91604. persCamera.maxZ = perspectiveCamera.zfar;
  91605. persCamera.minZ = perspectiveCamera.znear;
  91606. }
  91607. lastNode = persCamera;
  91608. }
  91609. }
  91610. }
  91611. // Empty node
  91612. if (!node.jointName) {
  91613. if (node.babylonNode) {
  91614. return node.babylonNode;
  91615. }
  91616. else if (lastNode === null) {
  91617. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91618. node.babylonNode = dummy;
  91619. lastNode = dummy;
  91620. }
  91621. }
  91622. if (lastNode !== null) {
  91623. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  91624. configureNodeFromMatrix(lastNode, node, parent);
  91625. }
  91626. else {
  91627. var translation = node.translation || [0, 0, 0];
  91628. var rotation = node.rotation || [0, 0, 0, 1];
  91629. var scale = node.scale || [1, 1, 1];
  91630. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  91631. }
  91632. lastNode.updateCache(true);
  91633. node.babylonNode = lastNode;
  91634. }
  91635. return lastNode;
  91636. };
  91637. /**
  91638. * Traverses nodes and creates them
  91639. */
  91640. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  91641. if (meshIncluded === void 0) { meshIncluded = false; }
  91642. var node = gltfRuntime.nodes[id];
  91643. var newNode = null;
  91644. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  91645. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  91646. meshIncluded = true;
  91647. }
  91648. else {
  91649. meshIncluded = false;
  91650. }
  91651. }
  91652. else {
  91653. meshIncluded = true;
  91654. }
  91655. if (!node.jointName && meshIncluded) {
  91656. newNode = importNode(gltfRuntime, node, id, parent);
  91657. if (newNode !== null) {
  91658. newNode.id = id;
  91659. newNode.parent = parent;
  91660. }
  91661. }
  91662. if (node.children) {
  91663. for (var i = 0; i < node.children.length; i++) {
  91664. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  91665. }
  91666. }
  91667. };
  91668. /**
  91669. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  91670. */
  91671. var postLoad = function (gltfRuntime) {
  91672. // Nodes
  91673. var currentScene = gltfRuntime.currentScene;
  91674. if (currentScene) {
  91675. for (var i = 0; i < currentScene.nodes.length; i++) {
  91676. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91677. }
  91678. }
  91679. else {
  91680. for (var thing in gltfRuntime.scenes) {
  91681. currentScene = gltfRuntime.scenes[thing];
  91682. for (var i = 0; i < currentScene.nodes.length; i++) {
  91683. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91684. }
  91685. }
  91686. }
  91687. // Set animations
  91688. loadAnimations(gltfRuntime);
  91689. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  91690. var skeleton = gltfRuntime.scene.skeletons[i];
  91691. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  91692. }
  91693. };
  91694. /**
  91695. * onBind shaderrs callback to set uniforms and matrices
  91696. */
  91697. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  91698. var materialValues = material.values || technique.parameters;
  91699. for (var unif in unTreatedUniforms) {
  91700. var uniform = unTreatedUniforms[unif];
  91701. var type = uniform.type;
  91702. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  91703. if (uniform.semantic && !uniform.source && !uniform.node) {
  91704. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  91705. }
  91706. else if (uniform.semantic && (uniform.source || uniform.node)) {
  91707. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  91708. if (source === null) {
  91709. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  91710. }
  91711. if (source === null) {
  91712. continue;
  91713. }
  91714. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  91715. }
  91716. }
  91717. else {
  91718. var value = materialValues[technique.uniforms[unif]];
  91719. if (!value) {
  91720. continue;
  91721. }
  91722. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91723. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  91724. if (texture === null || texture === undefined) {
  91725. continue;
  91726. }
  91727. shaderMaterial.getEffect().setTexture(unif, texture);
  91728. }
  91729. else {
  91730. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  91731. }
  91732. }
  91733. }
  91734. onSuccess(shaderMaterial);
  91735. };
  91736. /**
  91737. * Prepare uniforms to send the only one time
  91738. * Loads the appropriate textures
  91739. */
  91740. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  91741. var materialValues = material.values || technique.parameters;
  91742. var techniqueUniforms = technique.uniforms;
  91743. /**
  91744. * Prepare values here (not matrices)
  91745. */
  91746. for (var unif in unTreatedUniforms) {
  91747. var uniform = unTreatedUniforms[unif];
  91748. var type = uniform.type;
  91749. var value = materialValues[techniqueUniforms[unif]];
  91750. if (value === undefined) {
  91751. // In case the value is the same for all materials
  91752. value = uniform.value;
  91753. }
  91754. if (!value) {
  91755. continue;
  91756. }
  91757. var onLoadTexture = function (uniformName) {
  91758. return function (texture) {
  91759. if (uniform.value && uniformName) {
  91760. // Static uniform
  91761. shaderMaterial.setTexture(uniformName, texture);
  91762. delete unTreatedUniforms[uniformName];
  91763. }
  91764. };
  91765. };
  91766. // Texture (sampler2D)
  91767. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91768. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  91769. }
  91770. else {
  91771. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  91772. // Static uniform
  91773. delete unTreatedUniforms[unif];
  91774. }
  91775. }
  91776. }
  91777. };
  91778. /**
  91779. * Shader compilation failed
  91780. */
  91781. var onShaderCompileError = function (program, shaderMaterial, onError) {
  91782. return function (effect, error) {
  91783. shaderMaterial.dispose(true);
  91784. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  91785. };
  91786. };
  91787. /**
  91788. * Shader compilation success
  91789. */
  91790. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91791. return function (_) {
  91792. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91793. shaderMaterial.onBind = function (mesh) {
  91794. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91795. };
  91796. };
  91797. };
  91798. /**
  91799. * Returns the appropriate uniform if already handled by babylon
  91800. */
  91801. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91802. for (var unif in technique.uniforms) {
  91803. var uniform = technique.uniforms[unif];
  91804. var uniformParameter = technique.parameters[uniform];
  91805. if (tokenizer.currentIdentifier === unif) {
  91806. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91807. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91808. if (transformIndex !== -1) {
  91809. delete unTreatedUniforms[unif];
  91810. return babylonTransforms[transformIndex];
  91811. }
  91812. }
  91813. }
  91814. }
  91815. return tokenizer.currentIdentifier;
  91816. };
  91817. /**
  91818. * All shaders loaded. Create materials one by one
  91819. */
  91820. var importMaterials = function (gltfRuntime) {
  91821. // Create materials
  91822. for (var mat in gltfRuntime.materials) {
  91823. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91824. }
  91825. };
  91826. /**
  91827. * Implementation of the base glTF spec
  91828. */
  91829. var GLTFLoaderBase = /** @class */ (function () {
  91830. function GLTFLoaderBase() {
  91831. }
  91832. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91833. var gltfRuntime = {
  91834. extensions: {},
  91835. accessors: {},
  91836. buffers: {},
  91837. bufferViews: {},
  91838. meshes: {},
  91839. lights: {},
  91840. cameras: {},
  91841. nodes: {},
  91842. images: {},
  91843. textures: {},
  91844. shaders: {},
  91845. programs: {},
  91846. samplers: {},
  91847. techniques: {},
  91848. materials: {},
  91849. animations: {},
  91850. skins: {},
  91851. extensionsUsed: [],
  91852. scenes: {},
  91853. buffersCount: 0,
  91854. shaderscount: 0,
  91855. scene: scene,
  91856. rootUrl: rootUrl,
  91857. loadedBufferCount: 0,
  91858. loadedBufferViews: {},
  91859. loadedShaderCount: 0,
  91860. importOnlyMeshes: false,
  91861. dummyNodes: []
  91862. };
  91863. // Parse
  91864. if (parsedData.extensions) {
  91865. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91866. }
  91867. if (parsedData.extensionsUsed) {
  91868. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91869. }
  91870. if (parsedData.buffers) {
  91871. parseBuffers(parsedData.buffers, gltfRuntime);
  91872. }
  91873. if (parsedData.bufferViews) {
  91874. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91875. }
  91876. if (parsedData.accessors) {
  91877. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91878. }
  91879. if (parsedData.meshes) {
  91880. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91881. }
  91882. if (parsedData.lights) {
  91883. parseObject(parsedData.lights, "lights", gltfRuntime);
  91884. }
  91885. if (parsedData.cameras) {
  91886. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91887. }
  91888. if (parsedData.nodes) {
  91889. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91890. }
  91891. if (parsedData.images) {
  91892. parseObject(parsedData.images, "images", gltfRuntime);
  91893. }
  91894. if (parsedData.textures) {
  91895. parseObject(parsedData.textures, "textures", gltfRuntime);
  91896. }
  91897. if (parsedData.shaders) {
  91898. parseShaders(parsedData.shaders, gltfRuntime);
  91899. }
  91900. if (parsedData.programs) {
  91901. parseObject(parsedData.programs, "programs", gltfRuntime);
  91902. }
  91903. if (parsedData.samplers) {
  91904. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91905. }
  91906. if (parsedData.techniques) {
  91907. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91908. }
  91909. if (parsedData.materials) {
  91910. parseObject(parsedData.materials, "materials", gltfRuntime);
  91911. }
  91912. if (parsedData.animations) {
  91913. parseObject(parsedData.animations, "animations", gltfRuntime);
  91914. }
  91915. if (parsedData.skins) {
  91916. parseObject(parsedData.skins, "skins", gltfRuntime);
  91917. }
  91918. if (parsedData.scenes) {
  91919. gltfRuntime.scenes = parsedData.scenes;
  91920. }
  91921. if (parsedData.scene && parsedData.scenes) {
  91922. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91923. }
  91924. return gltfRuntime;
  91925. };
  91926. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91927. var buffer = gltfRuntime.buffers[id];
  91928. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91929. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91930. }
  91931. else {
  91932. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91933. if (request) {
  91934. onError(request.status + " " + request.statusText);
  91935. }
  91936. });
  91937. }
  91938. };
  91939. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91940. var texture = gltfRuntime.textures[id];
  91941. if (!texture || !texture.source) {
  91942. onError("");
  91943. return;
  91944. }
  91945. if (texture.babylonTexture) {
  91946. onSuccess(null);
  91947. return;
  91948. }
  91949. var source = gltfRuntime.images[texture.source];
  91950. if (BABYLON.Tools.IsBase64(source.uri)) {
  91951. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91952. }
  91953. else {
  91954. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91955. if (request) {
  91956. onError(request.status + " " + request.statusText);
  91957. }
  91958. });
  91959. }
  91960. };
  91961. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91962. var texture = gltfRuntime.textures[id];
  91963. if (texture.babylonTexture) {
  91964. onSuccess(texture.babylonTexture);
  91965. return;
  91966. }
  91967. var sampler = gltfRuntime.samplers[texture.sampler];
  91968. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91969. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91970. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91971. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91972. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91973. var blob = new Blob([buffer]);
  91974. var blobURL = URL.createObjectURL(blob);
  91975. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91976. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91977. if (sampler.wrapS !== undefined) {
  91978. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91979. }
  91980. if (sampler.wrapT !== undefined) {
  91981. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91982. }
  91983. newTexture.name = id;
  91984. texture.babylonTexture = newTexture;
  91985. onSuccess(newTexture);
  91986. };
  91987. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91988. var shader = gltfRuntime.shaders[id];
  91989. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91990. var shaderString = atob(shader.uri.split(",")[1]);
  91991. onSuccess(shaderString);
  91992. }
  91993. else {
  91994. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91995. if (request) {
  91996. onError(request.status + " " + request.statusText);
  91997. }
  91998. });
  91999. }
  92000. };
  92001. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92002. var material = gltfRuntime.materials[id];
  92003. if (!material.technique) {
  92004. if (onError) {
  92005. onError("No technique found.");
  92006. }
  92007. return;
  92008. }
  92009. var technique = gltfRuntime.techniques[material.technique];
  92010. if (!technique) {
  92011. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92012. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  92013. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92014. onSuccess(defaultMaterial);
  92015. return;
  92016. }
  92017. var program = gltfRuntime.programs[technique.program];
  92018. var states = technique.states;
  92019. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  92020. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  92021. var newVertexShader = "";
  92022. var newPixelShader = "";
  92023. var vertexTokenizer = new Tokenizer(vertexShader);
  92024. var pixelTokenizer = new Tokenizer(pixelShader);
  92025. var unTreatedUniforms = {};
  92026. var uniforms = [];
  92027. var attributes = [];
  92028. var samplers = [];
  92029. // Fill uniform, sampler2D and attributes
  92030. for (var unif in technique.uniforms) {
  92031. var uniform = technique.uniforms[unif];
  92032. var uniformParameter = technique.parameters[uniform];
  92033. unTreatedUniforms[unif] = uniformParameter;
  92034. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  92035. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  92036. if (transformIndex !== -1) {
  92037. uniforms.push(babylonTransforms[transformIndex]);
  92038. delete unTreatedUniforms[unif];
  92039. }
  92040. else {
  92041. uniforms.push(unif);
  92042. }
  92043. }
  92044. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  92045. samplers.push(unif);
  92046. }
  92047. else {
  92048. uniforms.push(unif);
  92049. }
  92050. }
  92051. for (var attr in technique.attributes) {
  92052. var attribute = technique.attributes[attr];
  92053. var attributeParameter = technique.parameters[attribute];
  92054. if (attributeParameter.semantic) {
  92055. attributes.push(getAttribute(attributeParameter));
  92056. }
  92057. }
  92058. // Configure vertex shader
  92059. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  92060. var tokenType = vertexTokenizer.currentToken;
  92061. if (tokenType !== ETokenType.IDENTIFIER) {
  92062. newVertexShader += vertexTokenizer.currentString;
  92063. continue;
  92064. }
  92065. var foundAttribute = false;
  92066. for (var attr in technique.attributes) {
  92067. var attribute = technique.attributes[attr];
  92068. var attributeParameter = technique.parameters[attribute];
  92069. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  92070. newVertexShader += getAttribute(attributeParameter);
  92071. foundAttribute = true;
  92072. break;
  92073. }
  92074. }
  92075. if (foundAttribute) {
  92076. continue;
  92077. }
  92078. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  92079. }
  92080. // Configure pixel shader
  92081. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  92082. var tokenType = pixelTokenizer.currentToken;
  92083. if (tokenType !== ETokenType.IDENTIFIER) {
  92084. newPixelShader += pixelTokenizer.currentString;
  92085. continue;
  92086. }
  92087. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  92088. }
  92089. // Create shader material
  92090. var shaderPath = {
  92091. vertex: program.vertexShader + id,
  92092. fragment: program.fragmentShader + id
  92093. };
  92094. var options = {
  92095. attributes: attributes,
  92096. uniforms: uniforms,
  92097. samplers: samplers,
  92098. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  92099. };
  92100. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  92101. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  92102. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  92103. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  92104. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  92105. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92106. if (states && states.functions) {
  92107. var functions = states.functions;
  92108. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  92109. shaderMaterial.backFaceCulling = false;
  92110. }
  92111. var blendFunc = functions.blendFuncSeparate;
  92112. if (blendFunc) {
  92113. 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) {
  92114. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  92115. }
  92116. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92117. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  92118. }
  92119. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92120. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  92121. }
  92122. 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) {
  92123. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  92124. }
  92125. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92126. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  92127. }
  92128. 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) {
  92129. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  92130. }
  92131. }
  92132. }
  92133. };
  92134. return GLTFLoaderBase;
  92135. }());
  92136. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  92137. /**
  92138. * glTF V1 Loader
  92139. */
  92140. var GLTFLoader = /** @class */ (function () {
  92141. function GLTFLoader() {
  92142. // #region Stubs for IGLTFLoader interface
  92143. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92144. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92145. this.compileMaterials = false;
  92146. this.useClipPlane = false;
  92147. this.compileShadowGenerators = false;
  92148. this.onDisposeObservable = new BABYLON.Observable();
  92149. this.onMeshLoadedObservable = new BABYLON.Observable();
  92150. this.onTextureLoadedObservable = new BABYLON.Observable();
  92151. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92152. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92153. this.onCompleteObservable = new BABYLON.Observable();
  92154. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92155. this.state = null;
  92156. }
  92157. GLTFLoader.RegisterExtension = function (extension) {
  92158. if (GLTFLoader.Extensions[extension.name]) {
  92159. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  92160. return;
  92161. }
  92162. GLTFLoader.Extensions[extension.name] = extension;
  92163. };
  92164. GLTFLoader.prototype.dispose = function () { };
  92165. // #endregion
  92166. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  92167. var _this = this;
  92168. scene.useRightHandedSystem = true;
  92169. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  92170. gltfRuntime.importOnlyMeshes = true;
  92171. if (meshesNames === "") {
  92172. gltfRuntime.importMeshesNames = [];
  92173. }
  92174. else if (typeof meshesNames === "string") {
  92175. gltfRuntime.importMeshesNames = [meshesNames];
  92176. }
  92177. else if (meshesNames && !(meshesNames instanceof Array)) {
  92178. gltfRuntime.importMeshesNames = [meshesNames];
  92179. }
  92180. else {
  92181. gltfRuntime.importMeshesNames = [];
  92182. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  92183. }
  92184. // Create nodes
  92185. _this._createNodes(gltfRuntime);
  92186. var meshes = new Array();
  92187. var skeletons = new Array();
  92188. // Fill arrays of meshes and skeletons
  92189. for (var nde in gltfRuntime.nodes) {
  92190. var node = gltfRuntime.nodes[nde];
  92191. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  92192. meshes.push(node.babylonNode);
  92193. }
  92194. }
  92195. for (var skl in gltfRuntime.skins) {
  92196. var skin = gltfRuntime.skins[skl];
  92197. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  92198. skeletons.push(skin.babylonSkeleton);
  92199. }
  92200. }
  92201. // Load buffers, shaders, materials, etc.
  92202. _this._loadBuffersAsync(gltfRuntime, function () {
  92203. _this._loadShadersAsync(gltfRuntime, function () {
  92204. importMaterials(gltfRuntime);
  92205. postLoad(gltfRuntime);
  92206. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  92207. onSuccess(meshes, [], skeletons);
  92208. }
  92209. });
  92210. }, onProgress);
  92211. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  92212. onSuccess(meshes, [], skeletons);
  92213. }
  92214. }, onError);
  92215. return true;
  92216. };
  92217. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92218. var _this = this;
  92219. return new Promise(function (resolve, reject) {
  92220. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  92221. resolve({
  92222. meshes: meshes,
  92223. particleSystems: particleSystems,
  92224. skeletons: skeletons
  92225. });
  92226. }, onProgress, function (message) {
  92227. reject(new Error(message));
  92228. });
  92229. });
  92230. };
  92231. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  92232. var _this = this;
  92233. scene.useRightHandedSystem = true;
  92234. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  92235. // Load runtime extensios
  92236. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  92237. // Create nodes
  92238. _this._createNodes(gltfRuntime);
  92239. // Load buffers, shaders, materials, etc.
  92240. _this._loadBuffersAsync(gltfRuntime, function () {
  92241. _this._loadShadersAsync(gltfRuntime, function () {
  92242. importMaterials(gltfRuntime);
  92243. postLoad(gltfRuntime);
  92244. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  92245. onSuccess();
  92246. }
  92247. });
  92248. });
  92249. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  92250. onSuccess();
  92251. }
  92252. }, onError);
  92253. }, onError);
  92254. };
  92255. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92256. var _this = this;
  92257. return new Promise(function (resolve, reject) {
  92258. _this._loadAsync(scene, data, rootUrl, function () {
  92259. resolve();
  92260. }, onProgress, function (message) {
  92261. reject(new Error(message));
  92262. });
  92263. });
  92264. };
  92265. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  92266. var hasShaders = false;
  92267. var processShader = function (sha, shader) {
  92268. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  92269. gltfRuntime.loadedShaderCount++;
  92270. if (shaderString) {
  92271. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  92272. }
  92273. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  92274. onload();
  92275. }
  92276. }, function () {
  92277. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  92278. });
  92279. };
  92280. for (var sha in gltfRuntime.shaders) {
  92281. hasShaders = true;
  92282. var shader = gltfRuntime.shaders[sha];
  92283. if (shader) {
  92284. processShader.bind(this, sha, shader)();
  92285. }
  92286. else {
  92287. BABYLON.Tools.Error("No shader named: " + sha);
  92288. }
  92289. }
  92290. if (!hasShaders) {
  92291. onload();
  92292. }
  92293. };
  92294. ;
  92295. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  92296. var hasBuffers = false;
  92297. var processBuffer = function (buf, buffer) {
  92298. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  92299. gltfRuntime.loadedBufferCount++;
  92300. if (bufferView) {
  92301. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  92302. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  92303. }
  92304. gltfRuntime.loadedBufferViews[buf] = bufferView;
  92305. }
  92306. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  92307. onLoad();
  92308. }
  92309. }, function () {
  92310. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  92311. });
  92312. };
  92313. for (var buf in gltfRuntime.buffers) {
  92314. hasBuffers = true;
  92315. var buffer = gltfRuntime.buffers[buf];
  92316. if (buffer) {
  92317. processBuffer.bind(this, buf, buffer)();
  92318. }
  92319. else {
  92320. BABYLON.Tools.Error("No buffer named: " + buf);
  92321. }
  92322. }
  92323. if (!hasBuffers) {
  92324. onLoad();
  92325. }
  92326. };
  92327. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  92328. var currentScene = gltfRuntime.currentScene;
  92329. if (currentScene) {
  92330. // Only one scene even if multiple scenes are defined
  92331. for (var i = 0; i < currentScene.nodes.length; i++) {
  92332. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92333. }
  92334. }
  92335. else {
  92336. // Load all scenes
  92337. for (var thing in gltfRuntime.scenes) {
  92338. currentScene = gltfRuntime.scenes[thing];
  92339. for (var i = 0; i < currentScene.nodes.length; i++) {
  92340. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92341. }
  92342. }
  92343. }
  92344. };
  92345. GLTFLoader.Extensions = {};
  92346. return GLTFLoader;
  92347. }());
  92348. GLTF1.GLTFLoader = GLTFLoader;
  92349. ;
  92350. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  92351. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92352. })(BABYLON || (BABYLON = {}));
  92353. //# sourceMappingURL=babylon.glTFLoader.js.map
  92354. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92355. var BABYLON;
  92356. (function (BABYLON) {
  92357. var GLTF1;
  92358. (function (GLTF1) {
  92359. /**
  92360. * Utils functions for GLTF
  92361. */
  92362. var GLTFUtils = /** @class */ (function () {
  92363. function GLTFUtils() {
  92364. }
  92365. /**
  92366. * Sets the given "parameter" matrix
  92367. * @param scene: the {BABYLON.Scene} object
  92368. * @param source: the source node where to pick the matrix
  92369. * @param parameter: the GLTF technique parameter
  92370. * @param uniformName: the name of the shader's uniform
  92371. * @param shaderMaterial: the shader material
  92372. */
  92373. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  92374. var mat = null;
  92375. if (parameter.semantic === "MODEL") {
  92376. mat = source.getWorldMatrix();
  92377. }
  92378. else if (parameter.semantic === "PROJECTION") {
  92379. mat = scene.getProjectionMatrix();
  92380. }
  92381. else if (parameter.semantic === "VIEW") {
  92382. mat = scene.getViewMatrix();
  92383. }
  92384. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  92385. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  92386. }
  92387. else if (parameter.semantic === "MODELVIEW") {
  92388. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  92389. }
  92390. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  92391. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  92392. }
  92393. else if (parameter.semantic === "MODELINVERSE") {
  92394. mat = source.getWorldMatrix().invert();
  92395. }
  92396. else if (parameter.semantic === "VIEWINVERSE") {
  92397. mat = scene.getViewMatrix().invert();
  92398. }
  92399. else if (parameter.semantic === "PROJECTIONINVERSE") {
  92400. mat = scene.getProjectionMatrix().invert();
  92401. }
  92402. else if (parameter.semantic === "MODELVIEWINVERSE") {
  92403. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  92404. }
  92405. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  92406. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  92407. }
  92408. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  92409. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  92410. }
  92411. else {
  92412. debugger;
  92413. }
  92414. if (mat) {
  92415. switch (parameter.type) {
  92416. case GLTF1.EParameterType.FLOAT_MAT2:
  92417. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  92418. break;
  92419. case GLTF1.EParameterType.FLOAT_MAT3:
  92420. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  92421. break;
  92422. case GLTF1.EParameterType.FLOAT_MAT4:
  92423. shaderMaterial.setMatrix(uniformName, mat);
  92424. break;
  92425. default: break;
  92426. }
  92427. }
  92428. };
  92429. /**
  92430. * Sets the given "parameter" matrix
  92431. * @param shaderMaterial: the shader material
  92432. * @param uniform: the name of the shader's uniform
  92433. * @param value: the value of the uniform
  92434. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  92435. */
  92436. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  92437. switch (type) {
  92438. case GLTF1.EParameterType.FLOAT:
  92439. shaderMaterial.setFloat(uniform, value);
  92440. return true;
  92441. case GLTF1.EParameterType.FLOAT_VEC2:
  92442. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  92443. return true;
  92444. case GLTF1.EParameterType.FLOAT_VEC3:
  92445. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  92446. return true;
  92447. case GLTF1.EParameterType.FLOAT_VEC4:
  92448. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  92449. return true;
  92450. default: return false;
  92451. }
  92452. };
  92453. /**
  92454. * Returns the wrap mode of the texture
  92455. * @param mode: the mode value
  92456. */
  92457. GLTFUtils.GetWrapMode = function (mode) {
  92458. switch (mode) {
  92459. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92460. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92461. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92462. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92463. }
  92464. };
  92465. /**
  92466. * Returns the byte stride giving an accessor
  92467. * @param accessor: the GLTF accessor objet
  92468. */
  92469. GLTFUtils.GetByteStrideFromType = function (accessor) {
  92470. // Needs this function since "byteStride" isn't requiered in glTF format
  92471. var type = accessor.type;
  92472. switch (type) {
  92473. case "VEC2": return 2;
  92474. case "VEC3": return 3;
  92475. case "VEC4": return 4;
  92476. case "MAT2": return 4;
  92477. case "MAT3": return 9;
  92478. case "MAT4": return 16;
  92479. default: return 1;
  92480. }
  92481. };
  92482. /**
  92483. * Returns the texture filter mode giving a mode value
  92484. * @param mode: the filter mode value
  92485. */
  92486. GLTFUtils.GetTextureFilterMode = function (mode) {
  92487. switch (mode) {
  92488. case GLTF1.ETextureFilterType.LINEAR:
  92489. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  92490. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92491. case GLTF1.ETextureFilterType.NEAREST:
  92492. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  92493. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  92494. }
  92495. };
  92496. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  92497. var byteOffset = bufferView.byteOffset + byteOffset;
  92498. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  92499. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  92500. throw new Error("Buffer access is out of range");
  92501. }
  92502. var buffer = loadedBufferView.buffer;
  92503. byteOffset += loadedBufferView.byteOffset;
  92504. switch (componentType) {
  92505. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  92506. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  92507. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  92508. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  92509. default: return new Float32Array(buffer, byteOffset, byteLength);
  92510. }
  92511. };
  92512. /**
  92513. * Returns a buffer from its accessor
  92514. * @param gltfRuntime: the GLTF runtime
  92515. * @param accessor: the GLTF accessor
  92516. */
  92517. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  92518. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  92519. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  92520. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  92521. };
  92522. /**
  92523. * Decodes a buffer view into a string
  92524. * @param view: the buffer view
  92525. */
  92526. GLTFUtils.DecodeBufferToText = function (view) {
  92527. var result = "";
  92528. var length = view.byteLength;
  92529. for (var i = 0; i < length; ++i) {
  92530. result += String.fromCharCode(view[i]);
  92531. }
  92532. return result;
  92533. };
  92534. /**
  92535. * Returns the default material of gltf. Related to
  92536. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  92537. * @param scene: the Babylon.js scene
  92538. */
  92539. GLTFUtils.GetDefaultMaterial = function (scene) {
  92540. if (!GLTFUtils._DefaultMaterial) {
  92541. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  92542. "precision highp float;",
  92543. "",
  92544. "uniform mat4 worldView;",
  92545. "uniform mat4 projection;",
  92546. "",
  92547. "attribute vec3 position;",
  92548. "",
  92549. "void main(void)",
  92550. "{",
  92551. " gl_Position = projection * worldView * vec4(position, 1.0);",
  92552. "}"
  92553. ].join("\n");
  92554. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  92555. "precision highp float;",
  92556. "",
  92557. "uniform vec4 u_emission;",
  92558. "",
  92559. "void main(void)",
  92560. "{",
  92561. " gl_FragColor = u_emission;",
  92562. "}"
  92563. ].join("\n");
  92564. var shaderPath = {
  92565. vertex: "GLTFDefaultMaterial",
  92566. fragment: "GLTFDefaultMaterial"
  92567. };
  92568. var options = {
  92569. attributes: ["position"],
  92570. uniforms: ["worldView", "projection", "u_emission"],
  92571. samplers: new Array(),
  92572. needAlphaBlending: false
  92573. };
  92574. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  92575. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  92576. }
  92577. return GLTFUtils._DefaultMaterial;
  92578. };
  92579. // The GLTF default material
  92580. GLTFUtils._DefaultMaterial = null;
  92581. return GLTFUtils;
  92582. }());
  92583. GLTF1.GLTFUtils = GLTFUtils;
  92584. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92585. })(BABYLON || (BABYLON = {}));
  92586. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  92587. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92588. var BABYLON;
  92589. (function (BABYLON) {
  92590. var GLTF1;
  92591. (function (GLTF1) {
  92592. var GLTFLoaderExtension = /** @class */ (function () {
  92593. function GLTFLoaderExtension(name) {
  92594. this._name = name;
  92595. }
  92596. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  92597. get: function () {
  92598. return this._name;
  92599. },
  92600. enumerable: true,
  92601. configurable: true
  92602. });
  92603. /**
  92604. * Defines an override for loading the runtime
  92605. * Return true to stop further extensions from loading the runtime
  92606. */
  92607. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92608. return false;
  92609. };
  92610. /**
  92611. * Defines an onverride for creating gltf runtime
  92612. * Return true to stop further extensions from creating the runtime
  92613. */
  92614. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92615. return false;
  92616. };
  92617. /**
  92618. * Defines an override for loading buffers
  92619. * Return true to stop further extensions from loading this buffer
  92620. */
  92621. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92622. return false;
  92623. };
  92624. /**
  92625. * Defines an override for loading texture buffers
  92626. * Return true to stop further extensions from loading this texture data
  92627. */
  92628. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92629. return false;
  92630. };
  92631. /**
  92632. * Defines an override for creating textures
  92633. * Return true to stop further extensions from loading this texture
  92634. */
  92635. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92636. return false;
  92637. };
  92638. /**
  92639. * Defines an override for loading shader strings
  92640. * Return true to stop further extensions from loading this shader data
  92641. */
  92642. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92643. return false;
  92644. };
  92645. /**
  92646. * Defines an override for loading materials
  92647. * Return true to stop further extensions from loading this material
  92648. */
  92649. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92650. return false;
  92651. };
  92652. // ---------
  92653. // Utilities
  92654. // ---------
  92655. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92656. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92657. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  92658. }, function () {
  92659. setTimeout(function () {
  92660. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92661. });
  92662. });
  92663. };
  92664. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92665. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92666. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  92667. }, function () {
  92668. setTimeout(function () {
  92669. onSuccess();
  92670. });
  92671. });
  92672. };
  92673. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92674. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92675. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92676. }, function () {
  92677. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92678. });
  92679. };
  92680. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  92681. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  92682. };
  92683. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92684. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92685. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92686. }, function () {
  92687. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92688. });
  92689. };
  92690. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92691. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92692. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92693. }, function () {
  92694. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92695. });
  92696. };
  92697. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92698. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92699. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92700. }, function () {
  92701. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92702. });
  92703. };
  92704. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92705. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92706. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92707. }, function () {
  92708. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92709. });
  92710. };
  92711. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  92712. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  92713. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  92714. if (func(loaderExtension)) {
  92715. return;
  92716. }
  92717. }
  92718. defaultFunc();
  92719. };
  92720. return GLTFLoaderExtension;
  92721. }());
  92722. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  92723. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92724. })(BABYLON || (BABYLON = {}));
  92725. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92726. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92727. var BABYLON;
  92728. (function (BABYLON) {
  92729. var GLTF1;
  92730. (function (GLTF1) {
  92731. var BinaryExtensionBufferName = "binary_glTF";
  92732. ;
  92733. ;
  92734. var GLTFBinaryExtension = /** @class */ (function (_super) {
  92735. __extends(GLTFBinaryExtension, _super);
  92736. function GLTFBinaryExtension() {
  92737. return _super.call(this, "KHR_binary_glTF") || this;
  92738. }
  92739. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92740. var extensionsUsed = data.json.extensionsUsed;
  92741. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  92742. return false;
  92743. }
  92744. this._bin = data.bin;
  92745. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92746. return true;
  92747. };
  92748. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92749. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  92750. return false;
  92751. }
  92752. if (id !== BinaryExtensionBufferName) {
  92753. return false;
  92754. }
  92755. onSuccess(this._bin);
  92756. return true;
  92757. };
  92758. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92759. var texture = gltfRuntime.textures[id];
  92760. var source = gltfRuntime.images[texture.source];
  92761. if (!source.extensions || !(this.name in source.extensions)) {
  92762. return false;
  92763. }
  92764. var sourceExt = source.extensions[this.name];
  92765. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  92766. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92767. onSuccess(buffer);
  92768. return true;
  92769. };
  92770. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92771. var shader = gltfRuntime.shaders[id];
  92772. if (!shader.extensions || !(this.name in shader.extensions)) {
  92773. return false;
  92774. }
  92775. var binaryExtensionShader = shader.extensions[this.name];
  92776. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  92777. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92778. setTimeout(function () {
  92779. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  92780. onSuccess(shaderString);
  92781. });
  92782. return true;
  92783. };
  92784. return GLTFBinaryExtension;
  92785. }(GLTF1.GLTFLoaderExtension));
  92786. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  92787. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  92788. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92789. })(BABYLON || (BABYLON = {}));
  92790. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92791. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92792. var BABYLON;
  92793. (function (BABYLON) {
  92794. var GLTF1;
  92795. (function (GLTF1) {
  92796. ;
  92797. ;
  92798. ;
  92799. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92800. __extends(GLTFMaterialsCommonExtension, _super);
  92801. function GLTFMaterialsCommonExtension() {
  92802. return _super.call(this, "KHR_materials_common") || this;
  92803. }
  92804. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92805. if (!gltfRuntime.extensions)
  92806. return false;
  92807. var extension = gltfRuntime.extensions[this.name];
  92808. if (!extension)
  92809. return false;
  92810. // Create lights
  92811. var lights = extension.lights;
  92812. if (lights) {
  92813. for (var thing in lights) {
  92814. var light = lights[thing];
  92815. switch (light.type) {
  92816. case "ambient":
  92817. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92818. var ambient = light.ambient;
  92819. if (ambient) {
  92820. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92821. }
  92822. break;
  92823. case "point":
  92824. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92825. var point = light.point;
  92826. if (point) {
  92827. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92828. }
  92829. break;
  92830. case "directional":
  92831. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92832. var directional = light.directional;
  92833. if (directional) {
  92834. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92835. }
  92836. break;
  92837. case "spot":
  92838. var spot = light.spot;
  92839. if (spot) {
  92840. 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);
  92841. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92842. }
  92843. break;
  92844. default:
  92845. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92846. break;
  92847. }
  92848. }
  92849. }
  92850. return false;
  92851. };
  92852. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92853. var material = gltfRuntime.materials[id];
  92854. if (!material || !material.extensions)
  92855. return false;
  92856. var extension = material.extensions[this.name];
  92857. if (!extension)
  92858. return false;
  92859. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92860. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92861. if (extension.technique === "CONSTANT") {
  92862. standardMaterial.disableLighting = true;
  92863. }
  92864. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92865. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92866. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92867. // Ambient
  92868. if (typeof extension.values.ambient === "string") {
  92869. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92870. }
  92871. else {
  92872. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92873. }
  92874. // Diffuse
  92875. if (typeof extension.values.diffuse === "string") {
  92876. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92877. }
  92878. else {
  92879. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92880. }
  92881. // Emission
  92882. if (typeof extension.values.emission === "string") {
  92883. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92884. }
  92885. else {
  92886. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92887. }
  92888. // Specular
  92889. if (typeof extension.values.specular === "string") {
  92890. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92891. }
  92892. else {
  92893. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92894. }
  92895. return true;
  92896. };
  92897. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92898. // Create buffer from texture url
  92899. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92900. // Create texture from buffer
  92901. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92902. }, onError);
  92903. };
  92904. return GLTFMaterialsCommonExtension;
  92905. }(GLTF1.GLTFLoaderExtension));
  92906. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92907. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92908. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92909. })(BABYLON || (BABYLON = {}));
  92910. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92911. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92912. var BABYLON;
  92913. (function (BABYLON) {
  92914. var GLTF2;
  92915. (function (GLTF2) {
  92916. var ArrayItem = /** @class */ (function () {
  92917. function ArrayItem() {
  92918. }
  92919. ArrayItem.Assign = function (values) {
  92920. if (values) {
  92921. for (var index = 0; index < values.length; index++) {
  92922. values[index]._index = index;
  92923. }
  92924. }
  92925. };
  92926. return ArrayItem;
  92927. }());
  92928. GLTF2.ArrayItem = ArrayItem;
  92929. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92930. })(BABYLON || (BABYLON = {}));
  92931. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92932. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92933. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92934. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92935. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92936. var BABYLON;
  92937. (function (BABYLON) {
  92938. var GLTF2;
  92939. (function (GLTF2) {
  92940. var GLTFLoader = /** @class */ (function () {
  92941. function GLTFLoader() {
  92942. this._completePromises = new Array();
  92943. this._disposed = false;
  92944. this._state = null;
  92945. this._extensions = {};
  92946. this._defaultSampler = {};
  92947. this._requests = new Array();
  92948. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92949. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92950. this.compileMaterials = false;
  92951. this.useClipPlane = false;
  92952. this.compileShadowGenerators = false;
  92953. this.onDisposeObservable = new BABYLON.Observable();
  92954. this.onMeshLoadedObservable = new BABYLON.Observable();
  92955. this.onTextureLoadedObservable = new BABYLON.Observable();
  92956. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92957. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92958. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92959. this.onCompleteObservable = new BABYLON.Observable();
  92960. }
  92961. GLTFLoader._Register = function (name, factory) {
  92962. if (GLTFLoader._Factories[name]) {
  92963. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92964. return;
  92965. }
  92966. GLTFLoader._Factories[name] = factory;
  92967. // Keep the order of registration so that extensions registered first are called first.
  92968. GLTFLoader._Names.push(name);
  92969. };
  92970. Object.defineProperty(GLTFLoader.prototype, "state", {
  92971. get: function () {
  92972. return this._state;
  92973. },
  92974. enumerable: true,
  92975. configurable: true
  92976. });
  92977. GLTFLoader.prototype.dispose = function () {
  92978. if (this._disposed) {
  92979. return;
  92980. }
  92981. this._disposed = true;
  92982. this.onDisposeObservable.notifyObservers(this);
  92983. this.onDisposeObservable.clear();
  92984. this._clear();
  92985. };
  92986. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92987. var _this = this;
  92988. return Promise.resolve().then(function () {
  92989. var nodes = null;
  92990. if (meshesNames) {
  92991. var nodeMap_1 = {};
  92992. if (_this._gltf.nodes) {
  92993. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92994. var node = _a[_i];
  92995. if (node.name) {
  92996. nodeMap_1[node.name] = node;
  92997. }
  92998. }
  92999. }
  93000. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  93001. nodes = names.map(function (name) {
  93002. var node = nodeMap_1[name];
  93003. if (!node) {
  93004. throw new Error("Failed to find node '" + name + "'");
  93005. }
  93006. return node;
  93007. });
  93008. }
  93009. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  93010. return {
  93011. meshes: _this._getMeshes(),
  93012. particleSystems: [],
  93013. skeletons: _this._getSkeletons(),
  93014. };
  93015. });
  93016. });
  93017. };
  93018. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  93019. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  93020. };
  93021. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  93022. var _this = this;
  93023. return Promise.resolve().then(function () {
  93024. _this._loadExtensions();
  93025. _this._babylonScene = scene;
  93026. _this._rootUrl = rootUrl;
  93027. _this._progressCallback = onProgress;
  93028. _this._state = BABYLON.GLTFLoaderState.Loading;
  93029. _this._loadData(data);
  93030. _this._checkExtensions();
  93031. var promises = new Array();
  93032. if (nodes) {
  93033. promises.push(_this._loadNodesAsync(nodes));
  93034. }
  93035. else {
  93036. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  93037. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  93038. }
  93039. if (_this.compileMaterials) {
  93040. promises.push(_this._compileMaterialsAsync());
  93041. }
  93042. if (_this.compileShadowGenerators) {
  93043. promises.push(_this._compileShadowGeneratorsAsync());
  93044. }
  93045. var resultPromise = Promise.all(promises).then(function () {
  93046. _this._state = BABYLON.GLTFLoaderState.Ready;
  93047. _this._startAnimations();
  93048. });
  93049. resultPromise.then(function () {
  93050. _this._rootBabylonMesh.setEnabled(true);
  93051. BABYLON.Tools.SetImmediate(function () {
  93052. if (!_this._disposed) {
  93053. Promise.all(_this._completePromises).then(function () {
  93054. _this._state = BABYLON.GLTFLoaderState.Complete;
  93055. _this.onCompleteObservable.notifyObservers(_this);
  93056. _this.onCompleteObservable.clear();
  93057. _this._clear();
  93058. }).catch(function (error) {
  93059. BABYLON.Tools.Error("glTF Loader: " + error.message);
  93060. _this._clear();
  93061. });
  93062. }
  93063. });
  93064. });
  93065. return resultPromise;
  93066. }).catch(function (error) {
  93067. BABYLON.Tools.Error("glTF Loader: " + error.message);
  93068. _this._clear();
  93069. throw error;
  93070. });
  93071. };
  93072. GLTFLoader.prototype._loadExtensions = function () {
  93073. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93074. var name_1 = _a[_i];
  93075. var extension = GLTFLoader._Factories[name_1](this);
  93076. this._extensions[name_1] = extension;
  93077. this.onExtensionLoadedObservable.notifyObservers(extension);
  93078. }
  93079. this.onExtensionLoadedObservable.clear();
  93080. };
  93081. GLTFLoader.prototype._loadData = function (data) {
  93082. this._gltf = data.json;
  93083. this._setupData();
  93084. if (data.bin) {
  93085. var buffers = this._gltf.buffers;
  93086. if (buffers && buffers[0] && !buffers[0].uri) {
  93087. var binaryBuffer = buffers[0];
  93088. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  93089. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  93090. }
  93091. binaryBuffer._data = Promise.resolve(data.bin);
  93092. }
  93093. else {
  93094. BABYLON.Tools.Warn("Unexpected BIN chunk");
  93095. }
  93096. }
  93097. };
  93098. GLTFLoader.prototype._setupData = function () {
  93099. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  93100. GLTF2.ArrayItem.Assign(this._gltf.animations);
  93101. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  93102. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  93103. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  93104. GLTF2.ArrayItem.Assign(this._gltf.images);
  93105. GLTF2.ArrayItem.Assign(this._gltf.materials);
  93106. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  93107. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  93108. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  93109. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  93110. GLTF2.ArrayItem.Assign(this._gltf.skins);
  93111. GLTF2.ArrayItem.Assign(this._gltf.textures);
  93112. if (this._gltf.nodes) {
  93113. var nodeParents = {};
  93114. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  93115. var node = _a[_i];
  93116. if (node.children) {
  93117. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  93118. var index = _c[_b];
  93119. nodeParents[index] = node._index;
  93120. }
  93121. }
  93122. }
  93123. var rootNode = this._createRootNode();
  93124. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  93125. var node = _e[_d];
  93126. var parentIndex = nodeParents[node._index];
  93127. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  93128. }
  93129. }
  93130. };
  93131. GLTFLoader.prototype._checkExtensions = function () {
  93132. if (this._gltf.extensionsRequired) {
  93133. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  93134. var name_2 = _a[_i];
  93135. var extension = this._extensions[name_2];
  93136. if (!extension || !extension.enabled) {
  93137. throw new Error("Require extension " + name_2 + " is not available");
  93138. }
  93139. }
  93140. }
  93141. };
  93142. GLTFLoader.prototype._createRootNode = function () {
  93143. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  93144. this._rootBabylonMesh.setEnabled(false);
  93145. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  93146. switch (this.coordinateSystemMode) {
  93147. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  93148. if (!this._babylonScene.useRightHandedSystem) {
  93149. rootNode.rotation = [0, 1, 0, 0];
  93150. rootNode.scale = [1, 1, -1];
  93151. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  93152. }
  93153. break;
  93154. }
  93155. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  93156. this._babylonScene.useRightHandedSystem = true;
  93157. break;
  93158. }
  93159. default: {
  93160. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  93161. }
  93162. }
  93163. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  93164. return rootNode;
  93165. };
  93166. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  93167. var promises = new Array();
  93168. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  93169. var node = nodes_1[_i];
  93170. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  93171. }
  93172. promises.push(this._loadAnimationsAsync());
  93173. return Promise.all(promises).then(function () { });
  93174. };
  93175. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  93176. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  93177. if (promise) {
  93178. return promise;
  93179. }
  93180. var promises = new Array();
  93181. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  93182. var index = _a[_i];
  93183. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  93184. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  93185. }
  93186. promises.push(this._loadAnimationsAsync());
  93187. return Promise.all(promises).then(function () { });
  93188. };
  93189. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  93190. if (node._babylonMesh) {
  93191. callback(node._babylonMesh);
  93192. }
  93193. if (node._primitiveBabylonMeshes) {
  93194. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  93195. var babylonMesh = _a[_i];
  93196. callback(babylonMesh);
  93197. }
  93198. }
  93199. };
  93200. GLTFLoader.prototype._getMeshes = function () {
  93201. var meshes = new Array();
  93202. // Root mesh is always first.
  93203. meshes.push(this._rootBabylonMesh);
  93204. var nodes = this._gltf.nodes;
  93205. if (nodes) {
  93206. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  93207. var node = nodes_2[_i];
  93208. this._forEachNodeMesh(node, function (mesh) {
  93209. meshes.push(mesh);
  93210. });
  93211. }
  93212. }
  93213. return meshes;
  93214. };
  93215. GLTFLoader.prototype._getSkeletons = function () {
  93216. var skeletons = new Array();
  93217. var skins = this._gltf.skins;
  93218. if (skins) {
  93219. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  93220. var skin = skins_1[_i];
  93221. if (skin._babylonSkeleton) {
  93222. skeletons.push(skin._babylonSkeleton);
  93223. }
  93224. }
  93225. }
  93226. return skeletons;
  93227. };
  93228. GLTFLoader.prototype._startAnimations = function () {
  93229. var animations = this._gltf.animations;
  93230. if (!animations) {
  93231. return;
  93232. }
  93233. switch (this.animationStartMode) {
  93234. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  93235. // do nothing
  93236. break;
  93237. }
  93238. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  93239. var animation = animations[0];
  93240. animation._babylonAnimationGroup.start(true);
  93241. break;
  93242. }
  93243. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  93244. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  93245. var animation = animations_1[_i];
  93246. animation._babylonAnimationGroup.start(true);
  93247. }
  93248. break;
  93249. }
  93250. default: {
  93251. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  93252. return;
  93253. }
  93254. }
  93255. };
  93256. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  93257. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  93258. if (promise) {
  93259. return promise;
  93260. }
  93261. if (node._babylonMesh) {
  93262. throw new Error(context + ": Invalid recursive node hierarchy");
  93263. }
  93264. var promises = new Array();
  93265. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  93266. node._babylonMesh = babylonMesh;
  93267. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93268. node._babylonAnimationTargets.push(babylonMesh);
  93269. GLTFLoader._LoadTransform(node, babylonMesh);
  93270. if (node.mesh != undefined) {
  93271. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  93272. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  93273. }
  93274. if (node.children) {
  93275. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  93276. var index = _a[_i];
  93277. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  93278. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  93279. }
  93280. }
  93281. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93282. return Promise.all(promises).then(function () { });
  93283. };
  93284. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  93285. // TODO: instancing
  93286. var _this = this;
  93287. var promises = new Array();
  93288. var primitives = mesh.primitives;
  93289. if (!primitives || primitives.length === 0) {
  93290. throw new Error(context + ": Primitives are missing");
  93291. }
  93292. GLTF2.ArrayItem.Assign(primitives);
  93293. if (primitives.length === 1) {
  93294. var primitive = primitives[0];
  93295. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  93296. }
  93297. else {
  93298. node._primitiveBabylonMeshes = [];
  93299. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  93300. var primitive = primitives_1[_i];
  93301. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  93302. node._primitiveBabylonMeshes.push(babylonMesh);
  93303. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  93304. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93305. }
  93306. }
  93307. if (node.skin != undefined) {
  93308. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  93309. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  93310. }
  93311. return Promise.all(promises).then(function () {
  93312. _this._forEachNodeMesh(node, function (babylonMesh) {
  93313. babylonMesh._refreshBoundingInfo(true);
  93314. });
  93315. });
  93316. };
  93317. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  93318. var _this = this;
  93319. var promises = new Array();
  93320. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  93321. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  93322. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  93323. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  93324. }));
  93325. if (primitive.material == undefined) {
  93326. babylonMesh.material = this._getDefaultMaterial();
  93327. }
  93328. else {
  93329. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  93330. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  93331. babylonMesh.material = babylonMaterial;
  93332. }));
  93333. }
  93334. return Promise.all(promises).then(function () { });
  93335. };
  93336. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93337. var _this = this;
  93338. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  93339. if (promise) {
  93340. return promise;
  93341. }
  93342. var attributes = primitive.attributes;
  93343. if (!attributes) {
  93344. throw new Error(context + ": Attributes are missing");
  93345. }
  93346. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  93347. // TODO: handle other primitive modes
  93348. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  93349. }
  93350. var promises = new Array();
  93351. var babylonVertexData = new BABYLON.VertexData();
  93352. if (primitive.indices == undefined) {
  93353. var positionAccessorIndex = attributes["POSITION"];
  93354. if (positionAccessorIndex != undefined) {
  93355. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  93356. babylonVertexData.indices = new Uint32Array(accessor.count);
  93357. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  93358. babylonVertexData.indices[i] = i;
  93359. }
  93360. }
  93361. }
  93362. else {
  93363. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  93364. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  93365. babylonVertexData.indices = data;
  93366. }));
  93367. }
  93368. var loadAttribute = function (attribute, kind) {
  93369. if (attributes[attribute] == undefined) {
  93370. return;
  93371. }
  93372. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93373. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93374. babylonMesh._delayInfo.push(kind);
  93375. }
  93376. if (attribute === "COLOR_0") {
  93377. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  93378. babylonMesh.hasVertexAlpha = true;
  93379. }
  93380. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93381. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93382. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  93383. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  93384. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  93385. }
  93386. babylonVertexData.set(attributeData, kind);
  93387. }));
  93388. };
  93389. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93390. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93391. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93392. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93393. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93394. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93395. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93396. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93397. return Promise.all(promises).then(function () {
  93398. return babylonVertexData;
  93399. });
  93400. };
  93401. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  93402. if (!primitive.targets) {
  93403. return;
  93404. }
  93405. if (node._numMorphTargets == undefined) {
  93406. node._numMorphTargets = primitive.targets.length;
  93407. }
  93408. else if (primitive.targets.length !== node._numMorphTargets) {
  93409. throw new Error(context + ": Primitives do not have the same number of targets");
  93410. }
  93411. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  93412. for (var index = 0; index < primitive.targets.length; index++) {
  93413. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  93414. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  93415. // TODO: tell the target whether it has positions, normals, tangents
  93416. }
  93417. };
  93418. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  93419. if (!primitive.targets) {
  93420. return Promise.resolve();
  93421. }
  93422. var promises = new Array();
  93423. var morphTargetManager = babylonMesh.morphTargetManager;
  93424. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  93425. var babylonMorphTarget = morphTargetManager.getTarget(index);
  93426. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  93427. }
  93428. return Promise.all(promises).then(function () { });
  93429. };
  93430. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  93431. var _this = this;
  93432. var promises = new Array();
  93433. var loadAttribute = function (attribute, setData) {
  93434. if (attributes[attribute] == undefined) {
  93435. return;
  93436. }
  93437. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93438. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93439. setData(data);
  93440. }));
  93441. };
  93442. loadAttribute("POSITION", function (data) {
  93443. if (babylonVertexData.positions) {
  93444. for (var i = 0; i < data.length; i++) {
  93445. data[i] += babylonVertexData.positions[i];
  93446. }
  93447. babylonMorphTarget.setPositions(data);
  93448. }
  93449. });
  93450. loadAttribute("NORMAL", function (data) {
  93451. if (babylonVertexData.normals) {
  93452. for (var i = 0; i < data.length; i++) {
  93453. data[i] += babylonVertexData.normals[i];
  93454. }
  93455. babylonMorphTarget.setNormals(data);
  93456. }
  93457. });
  93458. loadAttribute("TANGENT", function (data) {
  93459. if (babylonVertexData.tangents) {
  93460. // Tangent data for morph targets is stored as xyz delta.
  93461. // The vertexData.tangent is stored as xyzw.
  93462. // So we need to skip every fourth vertexData.tangent.
  93463. for (var i = 0, j = 0; i < data.length; i++) {
  93464. data[i] += babylonVertexData.tangents[j++];
  93465. if ((i + 1) % 3 == 0) {
  93466. j++;
  93467. }
  93468. }
  93469. babylonMorphTarget.setTangents(data);
  93470. }
  93471. });
  93472. return Promise.all(promises).then(function () { });
  93473. };
  93474. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  93475. if (accessor.componentType == 5126 /* FLOAT */) {
  93476. return data;
  93477. }
  93478. var factor = 1;
  93479. if (accessor.normalized) {
  93480. switch (accessor.componentType) {
  93481. case 5121 /* UNSIGNED_BYTE */: {
  93482. factor = 1 / 255;
  93483. break;
  93484. }
  93485. case 5123 /* UNSIGNED_SHORT */: {
  93486. factor = 1 / 65535;
  93487. break;
  93488. }
  93489. default: {
  93490. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93491. }
  93492. }
  93493. }
  93494. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  93495. for (var i = 0; i < result.length; i++) {
  93496. result[i] = data[i] * factor;
  93497. }
  93498. return result;
  93499. };
  93500. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  93501. var result = new Float32Array(data.length / 3 * 4);
  93502. var offset = 0;
  93503. for (var i = 0; i < result.length; i++) {
  93504. if ((i + 1) % 4 === 0) {
  93505. result[i] = 1;
  93506. }
  93507. else {
  93508. result[i] = data[offset++];
  93509. }
  93510. }
  93511. return result;
  93512. };
  93513. GLTFLoader._LoadTransform = function (node, babylonNode) {
  93514. var position = BABYLON.Vector3.Zero();
  93515. var rotation = BABYLON.Quaternion.Identity();
  93516. var scaling = BABYLON.Vector3.One();
  93517. if (node.matrix) {
  93518. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  93519. matrix.decompose(scaling, rotation, position);
  93520. }
  93521. else {
  93522. if (node.translation)
  93523. position = BABYLON.Vector3.FromArray(node.translation);
  93524. if (node.rotation)
  93525. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  93526. if (node.scale)
  93527. scaling = BABYLON.Vector3.FromArray(node.scale);
  93528. }
  93529. babylonNode.position = position;
  93530. babylonNode.rotationQuaternion = rotation;
  93531. babylonNode.scaling = scaling;
  93532. };
  93533. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  93534. var _this = this;
  93535. var assignSkeleton = function () {
  93536. _this._forEachNodeMesh(node, function (babylonMesh) {
  93537. babylonMesh.skeleton = skin._babylonSkeleton;
  93538. });
  93539. node._babylonMesh.parent = _this._rootBabylonMesh;
  93540. node._babylonMesh.position = BABYLON.Vector3.Zero();
  93541. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  93542. node._babylonMesh.scaling = BABYLON.Vector3.One();
  93543. };
  93544. if (skin._loaded) {
  93545. return skin._loaded.then(function () {
  93546. assignSkeleton();
  93547. });
  93548. }
  93549. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  93550. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  93551. var skeletonId = "skeleton" + skin._index;
  93552. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  93553. skin._babylonSkeleton = babylonSkeleton;
  93554. _this._loadBones(context, skin, inverseBindMatricesData);
  93555. assignSkeleton();
  93556. }));
  93557. };
  93558. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  93559. if (skin.inverseBindMatrices == undefined) {
  93560. return Promise.resolve(null);
  93561. }
  93562. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  93563. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93564. return data;
  93565. });
  93566. };
  93567. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  93568. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  93569. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93570. node._babylonAnimationTargets.push(babylonBone);
  93571. return babylonBone;
  93572. };
  93573. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  93574. var babylonBones = {};
  93575. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  93576. var index = _a[_i];
  93577. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  93578. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  93579. }
  93580. };
  93581. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  93582. var babylonBone = babylonBones[node._index];
  93583. if (babylonBone) {
  93584. return babylonBone;
  93585. }
  93586. var boneIndex = skin.joints.indexOf(node._index);
  93587. var baseMatrix = BABYLON.Matrix.Identity();
  93588. if (inverseBindMatricesData && boneIndex !== -1) {
  93589. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  93590. baseMatrix.invertToRef(baseMatrix);
  93591. }
  93592. var babylonParentBone = null;
  93593. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  93594. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  93595. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  93596. }
  93597. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  93598. babylonBones[node._index] = babylonBone;
  93599. return babylonBone;
  93600. };
  93601. GLTFLoader.prototype._getNodeMatrix = function (node) {
  93602. return node.matrix ?
  93603. BABYLON.Matrix.FromArray(node.matrix) :
  93604. 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());
  93605. };
  93606. GLTFLoader.prototype._loadAnimationsAsync = function () {
  93607. var animations = this._gltf.animations;
  93608. if (!animations) {
  93609. return Promise.resolve();
  93610. }
  93611. var promises = new Array();
  93612. for (var index = 0; index < animations.length; index++) {
  93613. var animation = animations[index];
  93614. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  93615. }
  93616. return Promise.all(promises).then(function () { });
  93617. };
  93618. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  93619. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  93620. animation._babylonAnimationGroup = babylonAnimationGroup;
  93621. var promises = new Array();
  93622. GLTF2.ArrayItem.Assign(animation.channels);
  93623. GLTF2.ArrayItem.Assign(animation.samplers);
  93624. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  93625. var channel = _a[_i];
  93626. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  93627. }
  93628. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  93629. return Promise.all(promises).then(function () {
  93630. babylonAnimationGroup.normalize();
  93631. });
  93632. };
  93633. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  93634. var _this = this;
  93635. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  93636. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  93637. return Promise.resolve();
  93638. }
  93639. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  93640. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  93641. var targetPath;
  93642. var animationType;
  93643. switch (channel.target.path) {
  93644. case "translation" /* TRANSLATION */: {
  93645. targetPath = "position";
  93646. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93647. break;
  93648. }
  93649. case "rotation" /* ROTATION */: {
  93650. targetPath = "rotationQuaternion";
  93651. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  93652. break;
  93653. }
  93654. case "scale" /* SCALE */: {
  93655. targetPath = "scaling";
  93656. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93657. break;
  93658. }
  93659. case "weights" /* WEIGHTS */: {
  93660. targetPath = "influence";
  93661. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  93662. break;
  93663. }
  93664. default: {
  93665. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  93666. }
  93667. }
  93668. var outputBufferOffset = 0;
  93669. var getNextOutputValue;
  93670. switch (targetPath) {
  93671. case "position": {
  93672. getNextOutputValue = function () {
  93673. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93674. outputBufferOffset += 3;
  93675. return value;
  93676. };
  93677. break;
  93678. }
  93679. case "rotationQuaternion": {
  93680. getNextOutputValue = function () {
  93681. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  93682. outputBufferOffset += 4;
  93683. return value;
  93684. };
  93685. break;
  93686. }
  93687. case "scaling": {
  93688. getNextOutputValue = function () {
  93689. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93690. outputBufferOffset += 3;
  93691. return value;
  93692. };
  93693. break;
  93694. }
  93695. case "influence": {
  93696. getNextOutputValue = function () {
  93697. var value = new Array(targetNode._numMorphTargets);
  93698. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  93699. value[i] = data.output[outputBufferOffset++];
  93700. }
  93701. return value;
  93702. };
  93703. break;
  93704. }
  93705. }
  93706. var getNextKey;
  93707. switch (data.interpolation) {
  93708. case "STEP" /* STEP */: {
  93709. getNextKey = function (frameIndex) { return ({
  93710. frame: data.input[frameIndex],
  93711. value: getNextOutputValue(),
  93712. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  93713. }); };
  93714. break;
  93715. }
  93716. case "LINEAR" /* LINEAR */: {
  93717. getNextKey = function (frameIndex) { return ({
  93718. frame: data.input[frameIndex],
  93719. value: getNextOutputValue()
  93720. }); };
  93721. break;
  93722. }
  93723. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93724. getNextKey = function (frameIndex) { return ({
  93725. frame: data.input[frameIndex],
  93726. inTangent: getNextOutputValue(),
  93727. value: getNextOutputValue(),
  93728. outTangent: getNextOutputValue()
  93729. }); };
  93730. break;
  93731. }
  93732. }
  93733. var keys;
  93734. if (data.input.length === 1) {
  93735. var key = getNextKey(0);
  93736. keys = [
  93737. { frame: key.frame, value: key.value },
  93738. { frame: key.frame + 1, value: key.value }
  93739. ];
  93740. }
  93741. else {
  93742. keys = new Array(data.input.length);
  93743. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  93744. keys[frameIndex] = getNextKey(frameIndex);
  93745. }
  93746. }
  93747. if (targetPath === "influence") {
  93748. var _loop_1 = function (targetIndex) {
  93749. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93750. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93751. babylonAnimation.setKeys(keys.map(function (key) { return ({
  93752. frame: key.frame,
  93753. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  93754. value: key.value[targetIndex],
  93755. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  93756. }); }));
  93757. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  93758. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  93759. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  93760. });
  93761. };
  93762. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  93763. _loop_1(targetIndex);
  93764. }
  93765. }
  93766. else {
  93767. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93768. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93769. babylonAnimation.setKeys(keys);
  93770. if (targetNode._babylonAnimationTargets) {
  93771. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  93772. var target = _a[_i];
  93773. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  93774. }
  93775. }
  93776. }
  93777. });
  93778. };
  93779. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  93780. if (sampler._data) {
  93781. return sampler._data;
  93782. }
  93783. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  93784. switch (interpolation) {
  93785. case "STEP" /* STEP */:
  93786. case "LINEAR" /* LINEAR */:
  93787. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93788. break;
  93789. }
  93790. default: {
  93791. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  93792. }
  93793. }
  93794. var inputData;
  93795. var outputData;
  93796. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  93797. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  93798. sampler._data = Promise.all([
  93799. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  93800. inputData = data;
  93801. }),
  93802. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  93803. outputData = data;
  93804. })
  93805. ]).then(function () {
  93806. return {
  93807. input: inputData,
  93808. interpolation: interpolation,
  93809. output: outputData,
  93810. };
  93811. });
  93812. return sampler._data;
  93813. };
  93814. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93815. if (buffer._data) {
  93816. return buffer._data;
  93817. }
  93818. if (!buffer.uri) {
  93819. throw new Error(context + ": Uri is missing");
  93820. }
  93821. buffer._data = this._loadUriAsync(context, buffer.uri);
  93822. return buffer._data;
  93823. };
  93824. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93825. if (bufferView._data) {
  93826. return bufferView._data;
  93827. }
  93828. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93829. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93830. try {
  93831. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93832. }
  93833. catch (e) {
  93834. throw new Error(context + ": " + e.message);
  93835. }
  93836. });
  93837. return bufferView._data;
  93838. };
  93839. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93840. var _this = this;
  93841. if (accessor.sparse) {
  93842. throw new Error(context + ": Sparse accessors are not currently supported");
  93843. }
  93844. if (accessor._data) {
  93845. return accessor._data;
  93846. }
  93847. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93848. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93849. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93850. var byteOffset = accessor.byteOffset || 0;
  93851. var byteStride = bufferView.byteStride;
  93852. if (byteStride === 0) {
  93853. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93854. }
  93855. try {
  93856. switch (accessor.componentType) {
  93857. case 5120 /* BYTE */: {
  93858. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93859. }
  93860. case 5121 /* UNSIGNED_BYTE */: {
  93861. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93862. }
  93863. case 5122 /* SHORT */: {
  93864. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93865. }
  93866. case 5123 /* UNSIGNED_SHORT */: {
  93867. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93868. }
  93869. case 5125 /* UNSIGNED_INT */: {
  93870. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93871. }
  93872. case 5126 /* FLOAT */: {
  93873. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93874. }
  93875. default: {
  93876. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93877. }
  93878. }
  93879. }
  93880. catch (e) {
  93881. throw new Error(context + ": " + e.messsage);
  93882. }
  93883. });
  93884. return accessor._data;
  93885. };
  93886. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93887. byteOffset += data.byteOffset;
  93888. var targetLength = count * numComponents;
  93889. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93890. return new typedArray(data.buffer, byteOffset, targetLength);
  93891. }
  93892. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93893. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93894. var targetBuffer = new typedArray(targetLength);
  93895. var sourceIndex = 0;
  93896. var targetIndex = 0;
  93897. while (targetIndex < targetLength) {
  93898. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93899. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93900. targetIndex++;
  93901. }
  93902. sourceIndex += elementStride;
  93903. }
  93904. return targetBuffer;
  93905. };
  93906. GLTFLoader.prototype._getDefaultMaterial = function () {
  93907. var id = "__gltf_default";
  93908. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93909. if (!babylonMaterial) {
  93910. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93911. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93912. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93913. babylonMaterial.metallic = 1;
  93914. babylonMaterial.roughness = 1;
  93915. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93916. }
  93917. return babylonMaterial;
  93918. };
  93919. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93920. var promises = new Array();
  93921. var babylonMaterial = material._babylonMaterial;
  93922. // Ensure metallic workflow
  93923. babylonMaterial.metallic = 1;
  93924. babylonMaterial.roughness = 1;
  93925. var properties = material.pbrMetallicRoughness;
  93926. if (properties) {
  93927. if (properties.baseColorFactor) {
  93928. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93929. babylonMaterial.alpha = properties.baseColorFactor[3];
  93930. }
  93931. else {
  93932. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93933. }
  93934. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93935. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93936. if (properties.baseColorTexture) {
  93937. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93938. babylonMaterial.albedoTexture = texture;
  93939. }));
  93940. }
  93941. if (properties.metallicRoughnessTexture) {
  93942. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93943. babylonMaterial.metallicTexture = texture;
  93944. }));
  93945. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93946. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93947. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93948. }
  93949. }
  93950. this._loadMaterialAlphaProperties(context, material);
  93951. return Promise.all(promises).then(function () { });
  93952. };
  93953. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  93954. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  93955. if (promise) {
  93956. return promise;
  93957. }
  93958. material._babylonMeshes = material._babylonMeshes || [];
  93959. material._babylonMeshes.push(babylonMesh);
  93960. if (!material._loaded) {
  93961. var promises = new Array();
  93962. var babylonMaterial = this._createMaterial(material);
  93963. material._babylonMaterial = babylonMaterial;
  93964. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93965. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93966. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93967. material._loaded = Promise.all(promises).then(function () { });
  93968. }
  93969. assign(material._babylonMaterial);
  93970. return material._loaded;
  93971. };
  93972. GLTFLoader.prototype._createMaterial = function (material) {
  93973. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93974. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93975. return babylonMaterial;
  93976. };
  93977. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93978. var promises = new Array();
  93979. var babylonMaterial = material._babylonMaterial;
  93980. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93981. if (material.doubleSided) {
  93982. babylonMaterial.backFaceCulling = false;
  93983. babylonMaterial.twoSidedLighting = true;
  93984. }
  93985. if (material.normalTexture) {
  93986. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93987. babylonMaterial.bumpTexture = texture;
  93988. }));
  93989. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93990. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93991. if (material.normalTexture.scale != undefined) {
  93992. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93993. }
  93994. }
  93995. if (material.occlusionTexture) {
  93996. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93997. babylonMaterial.ambientTexture = texture;
  93998. }));
  93999. babylonMaterial.useAmbientInGrayScale = true;
  94000. if (material.occlusionTexture.strength != undefined) {
  94001. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  94002. }
  94003. }
  94004. if (material.emissiveTexture) {
  94005. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  94006. babylonMaterial.emissiveTexture = texture;
  94007. }));
  94008. }
  94009. return Promise.all(promises).then(function () { });
  94010. };
  94011. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  94012. var babylonMaterial = material._babylonMaterial;
  94013. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  94014. switch (alphaMode) {
  94015. case "OPAQUE" /* OPAQUE */: {
  94016. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  94017. break;
  94018. }
  94019. case "MASK" /* MASK */: {
  94020. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  94021. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  94022. if (babylonMaterial.alpha) {
  94023. if (babylonMaterial.alpha === 0) {
  94024. babylonMaterial.alphaCutOff = 1;
  94025. }
  94026. else {
  94027. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  94028. }
  94029. babylonMaterial.alpha = 1;
  94030. }
  94031. if (babylonMaterial.albedoTexture) {
  94032. babylonMaterial.albedoTexture.hasAlpha = true;
  94033. }
  94034. break;
  94035. }
  94036. case "BLEND" /* BLEND */: {
  94037. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  94038. if (babylonMaterial.albedoTexture) {
  94039. babylonMaterial.albedoTexture.hasAlpha = true;
  94040. babylonMaterial.useAlphaFromAlbedoTexture = true;
  94041. }
  94042. break;
  94043. }
  94044. default: {
  94045. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  94046. }
  94047. }
  94048. };
  94049. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  94050. var _this = this;
  94051. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  94052. context = "#/textures/" + textureInfo.index;
  94053. var promises = new Array();
  94054. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  94055. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  94056. var deferred = new BABYLON.Deferred();
  94057. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  94058. if (!_this._disposed) {
  94059. deferred.resolve();
  94060. }
  94061. }, function (message, exception) {
  94062. if (!_this._disposed) {
  94063. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  94064. }
  94065. });
  94066. promises.push(deferred.promise);
  94067. babylonTexture.name = texture.name || "texture" + texture._index;
  94068. babylonTexture.wrapU = samplerData.wrapU;
  94069. babylonTexture.wrapV = samplerData.wrapV;
  94070. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  94071. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  94072. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  94073. babylonTexture.updateURL(objectURL);
  94074. }));
  94075. assign(babylonTexture);
  94076. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  94077. return Promise.all(promises).then(function () { });
  94078. };
  94079. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  94080. if (!sampler._data) {
  94081. sampler._data = {
  94082. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  94083. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  94084. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  94085. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  94086. };
  94087. }
  94088. ;
  94089. return sampler._data;
  94090. };
  94091. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  94092. if (image._objectURL) {
  94093. return image._objectURL;
  94094. }
  94095. var promise;
  94096. if (image.uri) {
  94097. promise = this._loadUriAsync(context, image.uri);
  94098. }
  94099. else {
  94100. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  94101. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  94102. }
  94103. image._objectURL = promise.then(function (data) {
  94104. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  94105. });
  94106. return image._objectURL;
  94107. };
  94108. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  94109. var _this = this;
  94110. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  94111. if (promise) {
  94112. return promise;
  94113. }
  94114. if (!GLTFLoader._ValidateUri(uri)) {
  94115. throw new Error(context + ": Uri '" + uri + "' is invalid");
  94116. }
  94117. if (BABYLON.Tools.IsBase64(uri)) {
  94118. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  94119. }
  94120. return new Promise(function (resolve, reject) {
  94121. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  94122. if (!_this._disposed) {
  94123. resolve(new Uint8Array(data));
  94124. }
  94125. }, function (event) {
  94126. if (!_this._disposed) {
  94127. try {
  94128. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  94129. request._lengthComputable = event.lengthComputable;
  94130. request._loaded = event.loaded;
  94131. request._total = event.total;
  94132. _this._onProgress();
  94133. }
  94134. }
  94135. catch (e) {
  94136. reject(e);
  94137. }
  94138. }
  94139. }, _this._babylonScene.database, true, function (request, exception) {
  94140. if (!_this._disposed) {
  94141. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  94142. }
  94143. });
  94144. _this._requests.push(request);
  94145. });
  94146. };
  94147. GLTFLoader.prototype._onProgress = function () {
  94148. if (!this._progressCallback) {
  94149. return;
  94150. }
  94151. var lengthComputable = true;
  94152. var loaded = 0;
  94153. var total = 0;
  94154. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94155. var request = _a[_i];
  94156. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  94157. return;
  94158. }
  94159. lengthComputable = lengthComputable && request._lengthComputable;
  94160. loaded += request._loaded;
  94161. total += request._total;
  94162. }
  94163. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  94164. };
  94165. GLTFLoader._GetProperty = function (context, array, index) {
  94166. if (!array || index == undefined || !array[index]) {
  94167. throw new Error(context + ": Failed to find index (" + index + ")");
  94168. }
  94169. return array[index];
  94170. };
  94171. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  94172. // Set defaults if undefined
  94173. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  94174. switch (mode) {
  94175. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  94176. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  94177. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  94178. default:
  94179. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  94180. return BABYLON.Texture.WRAP_ADDRESSMODE;
  94181. }
  94182. };
  94183. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  94184. // Set defaults if undefined
  94185. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  94186. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  94187. if (magFilter === 9729 /* LINEAR */) {
  94188. switch (minFilter) {
  94189. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  94190. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  94191. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  94192. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  94193. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  94194. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  94195. default:
  94196. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  94197. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  94198. }
  94199. }
  94200. else {
  94201. if (magFilter !== 9728 /* NEAREST */) {
  94202. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  94203. }
  94204. switch (minFilter) {
  94205. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  94206. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  94207. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  94208. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  94209. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  94210. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  94211. default:
  94212. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  94213. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  94214. }
  94215. }
  94216. };
  94217. GLTFLoader._GetNumComponents = function (context, type) {
  94218. switch (type) {
  94219. case "SCALAR": return 1;
  94220. case "VEC2": return 2;
  94221. case "VEC3": return 3;
  94222. case "VEC4": return 4;
  94223. case "MAT2": return 4;
  94224. case "MAT3": return 9;
  94225. case "MAT4": return 16;
  94226. }
  94227. throw new Error(context + ": Invalid type (" + type + ")");
  94228. };
  94229. GLTFLoader._ValidateUri = function (uri) {
  94230. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  94231. };
  94232. GLTFLoader.prototype._compileMaterialsAsync = function () {
  94233. var promises = new Array();
  94234. if (this._gltf.materials) {
  94235. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  94236. var material = _a[_i];
  94237. var babylonMaterial = material._babylonMaterial;
  94238. var babylonMeshes = material._babylonMeshes;
  94239. if (babylonMaterial && babylonMeshes) {
  94240. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  94241. var babylonMesh = babylonMeshes_1[_b];
  94242. // Ensure nonUniformScaling is set if necessary.
  94243. babylonMesh.computeWorldMatrix(true);
  94244. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  94245. if (this.useClipPlane) {
  94246. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  94247. }
  94248. }
  94249. }
  94250. }
  94251. }
  94252. return Promise.all(promises).then(function () { });
  94253. };
  94254. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  94255. var promises = new Array();
  94256. var lights = this._babylonScene.lights;
  94257. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  94258. var light = lights_1[_i];
  94259. var generator = light.getShadowGenerator();
  94260. if (generator) {
  94261. promises.push(generator.forceCompilationAsync());
  94262. }
  94263. }
  94264. return Promise.all(promises).then(function () { });
  94265. };
  94266. GLTFLoader.prototype._clear = function () {
  94267. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94268. var request = _a[_i];
  94269. request.abort();
  94270. }
  94271. this._requests.length = 0;
  94272. if (this._gltf && this._gltf.images) {
  94273. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  94274. var image = _c[_b];
  94275. if (image._objectURL) {
  94276. image._objectURL.then(function (value) {
  94277. URL.revokeObjectURL(value);
  94278. });
  94279. image._objectURL = undefined;
  94280. }
  94281. }
  94282. }
  94283. delete this._gltf;
  94284. delete this._babylonScene;
  94285. this._completePromises.length = 0;
  94286. for (var name_3 in this._extensions) {
  94287. this._extensions[name_3].dispose();
  94288. }
  94289. this._extensions = {};
  94290. delete this._rootBabylonMesh;
  94291. delete this._progressCallback;
  94292. this.onMeshLoadedObservable.clear();
  94293. this.onTextureLoadedObservable.clear();
  94294. this.onMaterialLoadedObservable.clear();
  94295. };
  94296. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  94297. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  94298. var name_4 = _a[_i];
  94299. var extension = this._extensions[name_4];
  94300. if (extension.enabled) {
  94301. var promise = actionAsync(extension);
  94302. if (promise) {
  94303. return promise;
  94304. }
  94305. }
  94306. }
  94307. return null;
  94308. };
  94309. GLTFLoader._Names = new Array();
  94310. GLTFLoader._Factories = {};
  94311. return GLTFLoader;
  94312. }());
  94313. GLTF2.GLTFLoader = GLTFLoader;
  94314. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  94315. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94316. })(BABYLON || (BABYLON = {}));
  94317. //# sourceMappingURL=babylon.glTFLoader.js.map
  94318. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  94319. var BABYLON;
  94320. (function (BABYLON) {
  94321. var GLTF2;
  94322. (function (GLTF2) {
  94323. var GLTFLoaderExtension = /** @class */ (function () {
  94324. function GLTFLoaderExtension(loader) {
  94325. this.enabled = true;
  94326. this._loader = loader;
  94327. }
  94328. GLTFLoaderExtension.prototype.dispose = function () {
  94329. delete this._loader;
  94330. };
  94331. // #region Overridable Methods
  94332. /** Override this method to modify the default behavior for loading scenes. */
  94333. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  94334. /** Override this method to modify the default behavior for loading nodes. */
  94335. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  94336. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  94337. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  94338. /** Override this method to modify the default behavior for loading materials. */
  94339. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  94340. /** Override this method to modify the default behavior for loading uris. */
  94341. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  94342. // #endregion
  94343. /** Helper method called by a loader extension to load an glTF extension. */
  94344. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  94345. if (!property.extensions) {
  94346. return null;
  94347. }
  94348. var extensions = property.extensions;
  94349. var extension = extensions[this.name];
  94350. if (!extension) {
  94351. return null;
  94352. }
  94353. // Clear out the extension before executing the action to avoid recursing into the same property.
  94354. delete extensions[this.name];
  94355. try {
  94356. return actionAsync(context + "/extensions/" + this.name, extension);
  94357. }
  94358. finally {
  94359. // Restore the extension after executing the action.
  94360. extensions[this.name] = extension;
  94361. }
  94362. };
  94363. /** Helper method called by the loader to allow extensions to override loading scenes. */
  94364. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  94365. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  94366. };
  94367. /** Helper method called by the loader to allow extensions to override loading nodes. */
  94368. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  94369. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  94370. };
  94371. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  94372. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  94373. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  94374. };
  94375. /** Helper method called by the loader to allow extensions to override loading materials. */
  94376. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  94377. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  94378. };
  94379. /** Helper method called by the loader to allow extensions to override loading uris. */
  94380. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  94381. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  94382. };
  94383. return GLTFLoaderExtension;
  94384. }());
  94385. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  94386. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94387. })(BABYLON || (BABYLON = {}));
  94388. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  94389. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94390. var BABYLON;
  94391. (function (BABYLON) {
  94392. var GLTF2;
  94393. (function (GLTF2) {
  94394. var Extensions;
  94395. (function (Extensions) {
  94396. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  94397. var NAME = "MSFT_lod";
  94398. var MSFT_lod = /** @class */ (function (_super) {
  94399. __extends(MSFT_lod, _super);
  94400. function MSFT_lod() {
  94401. var _this = _super !== null && _super.apply(this, arguments) || this;
  94402. _this.name = NAME;
  94403. /**
  94404. * Maximum number of LODs to load, starting from the lowest LOD.
  94405. */
  94406. _this.maxLODsToLoad = Number.MAX_VALUE;
  94407. _this._loadingNodeLOD = null;
  94408. _this._loadNodeSignals = {};
  94409. _this._loadingMaterialLOD = null;
  94410. _this._loadMaterialSignals = {};
  94411. return _this;
  94412. }
  94413. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  94414. var _this = this;
  94415. return this._loadExtensionAsync(context, node, function (context, extension) {
  94416. var firstPromise;
  94417. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  94418. var _loop_1 = function (indexLOD) {
  94419. var nodeLOD = nodeLODs[indexLOD];
  94420. if (indexLOD !== 0) {
  94421. _this._loadingNodeLOD = nodeLOD;
  94422. if (!_this._loadNodeSignals[nodeLOD._index]) {
  94423. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  94424. }
  94425. }
  94426. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  94427. if (indexLOD !== 0) {
  94428. var previousNodeLOD = nodeLODs[indexLOD - 1];
  94429. if (previousNodeLOD._babylonMesh) {
  94430. previousNodeLOD._babylonMesh.dispose();
  94431. delete previousNodeLOD._babylonMesh;
  94432. }
  94433. }
  94434. if (indexLOD !== nodeLODs.length - 1) {
  94435. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  94436. if (_this._loadNodeSignals[nodeIndex]) {
  94437. _this._loadNodeSignals[nodeIndex].resolve();
  94438. delete _this._loadNodeSignals[nodeIndex];
  94439. }
  94440. }
  94441. });
  94442. if (indexLOD === 0) {
  94443. firstPromise = promise;
  94444. }
  94445. else {
  94446. _this._loader._completePromises.push(promise);
  94447. _this._loadingNodeLOD = null;
  94448. }
  94449. };
  94450. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  94451. _loop_1(indexLOD);
  94452. }
  94453. return firstPromise;
  94454. });
  94455. };
  94456. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94457. var _this = this;
  94458. // Don't load material LODs if already loading a node LOD.
  94459. if (this._loadingNodeLOD) {
  94460. return null;
  94461. }
  94462. return this._loadExtensionAsync(context, material, function (context, extension) {
  94463. var firstPromise;
  94464. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  94465. var _loop_2 = function (indexLOD) {
  94466. var materialLOD = materialLODs[indexLOD];
  94467. if (indexLOD !== 0) {
  94468. _this._loadingMaterialLOD = materialLOD;
  94469. if (!_this._loadMaterialSignals[materialLOD._index]) {
  94470. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  94471. }
  94472. }
  94473. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  94474. if (indexLOD !== 0) {
  94475. assign(materialLOD._babylonMaterial);
  94476. var previousMaterialLOD = materialLODs[indexLOD - 1];
  94477. if (previousMaterialLOD._babylonMaterial) {
  94478. previousMaterialLOD._babylonMaterial.dispose();
  94479. delete previousMaterialLOD._babylonMaterial;
  94480. }
  94481. }
  94482. if (indexLOD !== materialLODs.length - 1) {
  94483. var materialIndex = materialLODs[indexLOD + 1]._index;
  94484. if (_this._loadMaterialSignals[materialIndex]) {
  94485. _this._loadMaterialSignals[materialIndex].resolve();
  94486. delete _this._loadMaterialSignals[materialIndex];
  94487. }
  94488. }
  94489. });
  94490. if (indexLOD === 0) {
  94491. firstPromise = promise;
  94492. }
  94493. else {
  94494. _this._loader._completePromises.push(promise);
  94495. _this._loadingMaterialLOD = null;
  94496. }
  94497. };
  94498. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  94499. _loop_2(indexLOD);
  94500. }
  94501. return firstPromise;
  94502. });
  94503. };
  94504. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  94505. var _this = this;
  94506. // Defer the loading of uris if loading a material or node LOD.
  94507. if (this._loadingMaterialLOD) {
  94508. var index = this._loadingMaterialLOD._index;
  94509. return this._loadMaterialSignals[index].promise.then(function () {
  94510. return _this._loader._loadUriAsync(context, uri);
  94511. });
  94512. }
  94513. else if (this._loadingNodeLOD) {
  94514. var index = this._loadingNodeLOD._index;
  94515. return this._loadNodeSignals[index].promise.then(function () {
  94516. return _this._loader._loadUriAsync(context, uri);
  94517. });
  94518. }
  94519. return null;
  94520. };
  94521. /**
  94522. * Gets an array of LOD properties from lowest to highest.
  94523. */
  94524. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  94525. if (this.maxLODsToLoad <= 0) {
  94526. throw new Error("maxLODsToLoad must be greater than zero");
  94527. }
  94528. var properties = new Array();
  94529. for (var i = ids.length - 1; i >= 0; i--) {
  94530. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  94531. if (properties.length === this.maxLODsToLoad) {
  94532. return properties;
  94533. }
  94534. }
  94535. properties.push(property);
  94536. return properties;
  94537. };
  94538. return MSFT_lod;
  94539. }(GLTF2.GLTFLoaderExtension));
  94540. Extensions.MSFT_lod = MSFT_lod;
  94541. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  94542. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94543. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94544. })(BABYLON || (BABYLON = {}));
  94545. //# sourceMappingURL=MSFT_lod.js.map
  94546. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94547. var BABYLON;
  94548. (function (BABYLON) {
  94549. var GLTF2;
  94550. (function (GLTF2) {
  94551. var Extensions;
  94552. (function (Extensions) {
  94553. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  94554. var NAME = "KHR_draco_mesh_compression";
  94555. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  94556. __extends(KHR_draco_mesh_compression, _super);
  94557. function KHR_draco_mesh_compression(loader) {
  94558. var _this = _super.call(this, loader) || this;
  94559. _this.name = NAME;
  94560. _this._dracoCompression = null;
  94561. // Disable extension if decoder is not available.
  94562. if (!BABYLON.DracoCompression.DecoderUrl) {
  94563. _this.enabled = false;
  94564. }
  94565. return _this;
  94566. }
  94567. KHR_draco_mesh_compression.prototype.dispose = function () {
  94568. if (this._dracoCompression) {
  94569. this._dracoCompression.dispose();
  94570. }
  94571. _super.prototype.dispose.call(this);
  94572. };
  94573. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94574. var _this = this;
  94575. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  94576. if (primitive.mode != undefined) {
  94577. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  94578. primitive.mode !== 4 /* TRIANGLES */) {
  94579. throw new Error(context + ": Unsupported mode " + primitive.mode);
  94580. }
  94581. // TODO: handle triangle strips
  94582. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  94583. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  94584. }
  94585. }
  94586. var attributes = {};
  94587. var loadAttribute = function (name, kind) {
  94588. var uniqueId = extension.attributes[name];
  94589. if (uniqueId == undefined) {
  94590. return;
  94591. }
  94592. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94593. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94594. babylonMesh._delayInfo.push(kind);
  94595. }
  94596. attributes[kind] = uniqueId;
  94597. };
  94598. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94599. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94600. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94601. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94602. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94603. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94604. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94605. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94606. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  94607. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  94608. try {
  94609. if (!_this._dracoCompression) {
  94610. _this._dracoCompression = new BABYLON.DracoCompression();
  94611. }
  94612. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  94613. }
  94614. catch (e) {
  94615. throw new Error(context + ": " + e.message);
  94616. }
  94617. });
  94618. });
  94619. };
  94620. return KHR_draco_mesh_compression;
  94621. }(GLTF2.GLTFLoaderExtension));
  94622. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  94623. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  94624. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94625. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94626. })(BABYLON || (BABYLON = {}));
  94627. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  94628. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94629. var BABYLON;
  94630. (function (BABYLON) {
  94631. var GLTF2;
  94632. (function (GLTF2) {
  94633. var Extensions;
  94634. (function (Extensions) {
  94635. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  94636. var NAME = "KHR_materials_pbrSpecularGlossiness";
  94637. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  94638. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  94639. function KHR_materials_pbrSpecularGlossiness() {
  94640. var _this = _super !== null && _super.apply(this, arguments) || this;
  94641. _this.name = NAME;
  94642. return _this;
  94643. }
  94644. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94645. var _this = this;
  94646. return this._loadExtensionAsync(context, material, function (context, extension) {
  94647. material._babylonMeshes = material._babylonMeshes || [];
  94648. material._babylonMeshes.push(babylonMesh);
  94649. if (!material._loaded) {
  94650. var promises = new Array();
  94651. var babylonMaterial = _this._loader._createMaterial(material);
  94652. material._babylonMaterial = babylonMaterial;
  94653. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  94654. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  94655. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94656. material._loaded = Promise.all(promises).then(function () { });
  94657. }
  94658. assign(material._babylonMaterial);
  94659. return material._loaded;
  94660. });
  94661. };
  94662. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  94663. var promises = new Array();
  94664. var babylonMaterial = material._babylonMaterial;
  94665. if (properties.diffuseFactor) {
  94666. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  94667. babylonMaterial.alpha = properties.diffuseFactor[3];
  94668. }
  94669. else {
  94670. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94671. }
  94672. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  94673. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  94674. if (properties.diffuseTexture) {
  94675. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  94676. babylonMaterial.albedoTexture = texture;
  94677. }));
  94678. }
  94679. if (properties.specularGlossinessTexture) {
  94680. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  94681. babylonMaterial.reflectivityTexture = texture;
  94682. }));
  94683. babylonMaterial.reflectivityTexture.hasAlpha = true;
  94684. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  94685. }
  94686. this._loader._loadMaterialAlphaProperties(context, material);
  94687. return Promise.all(promises).then(function () { });
  94688. };
  94689. return KHR_materials_pbrSpecularGlossiness;
  94690. }(GLTF2.GLTFLoaderExtension));
  94691. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  94692. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  94693. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94694. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94695. })(BABYLON || (BABYLON = {}));
  94696. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  94697. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94698. var BABYLON;
  94699. (function (BABYLON) {
  94700. var GLTF2;
  94701. (function (GLTF2) {
  94702. var Extensions;
  94703. (function (Extensions) {
  94704. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  94705. var NAME = "KHR_lights";
  94706. var LightType;
  94707. (function (LightType) {
  94708. LightType["AMBIENT"] = "ambient";
  94709. LightType["DIRECTIONAL"] = "directional";
  94710. LightType["POINT"] = "point";
  94711. LightType["SPOT"] = "spot";
  94712. })(LightType || (LightType = {}));
  94713. var KHR_lights = /** @class */ (function (_super) {
  94714. __extends(KHR_lights, _super);
  94715. function KHR_lights() {
  94716. var _this = _super !== null && _super.apply(this, arguments) || this;
  94717. _this.name = NAME;
  94718. return _this;
  94719. }
  94720. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  94721. var _this = this;
  94722. return this._loadExtensionAsync(context, scene, function (context, extension) {
  94723. var promise = _this._loader._loadSceneAsync(context, scene);
  94724. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94725. if (light.type !== LightType.AMBIENT) {
  94726. throw new Error(context + ": Only ambient lights are allowed on a scene");
  94727. }
  94728. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  94729. return promise;
  94730. });
  94731. };
  94732. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  94733. var _this = this;
  94734. return this._loadExtensionAsync(context, node, function (context, extension) {
  94735. var promise = _this._loader._loadNodeAsync(context, node);
  94736. var babylonLight;
  94737. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94738. var name = node._babylonMesh.name;
  94739. switch (light.type) {
  94740. case LightType.AMBIENT: {
  94741. throw new Error(context + ": Ambient lights are not allowed on a node");
  94742. }
  94743. case LightType.DIRECTIONAL: {
  94744. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  94745. break;
  94746. }
  94747. case LightType.POINT: {
  94748. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  94749. break;
  94750. }
  94751. case LightType.SPOT: {
  94752. var spotLight = light;
  94753. // TODO: support inner and outer cone angles
  94754. //const innerConeAngle = spotLight.innerConeAngle || 0;
  94755. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  94756. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  94757. break;
  94758. }
  94759. default: {
  94760. throw new Error(context + ": Invalid light type (" + light.type + ")");
  94761. }
  94762. }
  94763. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  94764. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  94765. babylonLight.parent = node._babylonMesh;
  94766. return promise;
  94767. });
  94768. };
  94769. Object.defineProperty(KHR_lights.prototype, "_lights", {
  94770. get: function () {
  94771. var extensions = this._loader._gltf.extensions;
  94772. if (!extensions || !extensions[this.name]) {
  94773. throw new Error("#/extensions: '" + this.name + "' not found");
  94774. }
  94775. var extension = extensions[this.name];
  94776. return extension.lights;
  94777. },
  94778. enumerable: true,
  94779. configurable: true
  94780. });
  94781. return KHR_lights;
  94782. }(GLTF2.GLTFLoaderExtension));
  94783. Extensions.KHR_lights = KHR_lights;
  94784. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  94785. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94786. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94787. })(BABYLON || (BABYLON = {}));
  94788. //# sourceMappingURL=KHR_lights.js.map
  94789. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94790. globalObject["BABYLON"] = BABYLON;
  94791. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;var GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode ;var GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode ;var GLTFLoaderState = BABYLON.GLTFLoaderState ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;
  94792. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState ,GLTFLoaderCoordinateSystemMode ,GLTFLoaderAnimationStartMode ,GLTFLoaderState ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 };